PHP uses Phpexcel to export table data

Source: Internet
Author: User
Tags rtrim

The project needs to export the data in the table, found on the Internet find phpexcel good use. Share now

Phpexcel

  1. if (!defined (' BasePath ')) exit (' No Direct script access allowed ');
  2. Material Hair Material List details
  3. Class read_write{
  4. /**
  5. * $name: Selected type (csv,excel2003,2007)
  6. * $titles: Header array
  7. * $querys: The array returned by the query $query->result_array ();
  8. * $filename: Saved file name
  9. */
  10. function Write_factory ($titles, $querys, $filename, $name = "EXCEL2003") {
  11. $CI = &get_instance ();
  12. $filename =mb_convert_encoding ($filename, "GBK", "UTF-8");
  13. Switch ($name) {
  14. Case "CSV":
  15. $CI->excel->write_csv ($titles, $querys, $filename);
  16. Break
  17. Case "EXCEL2003":
  18. $CI->excel->write_excel2003 ($titles, $querys, $filename);
  19. Break
  20. Case "EXCEL2007":
  21. $CI->excel->write_excel2007 ($titles, $querys, $filename);
  22. Break
  23. }
  24. }
  25. /**
  26. * $name:
  27. */
  28. function Read_facotry ($filePath, $sql, $sheet =0, $curRow =2, $riqi =true, $merge =false, $mergeCol = "B") {
  29. $CI = &get_instance ();
  30. $name = $this->_file_extend ($filePath);
  31. Switch ($name) {
  32. Case "CSV":
  33. $CI->excel->read_csv ($filePath, $sql, $sheet, $curRow, $riqi, $merge, $mergeCol);
  34. Break
  35. Case "XLS":
  36. $CI->excel->read_2003excel ($filePath, $sql, $sheet, $curRow, $riqi, $merge, $mergeCol);
  37. Break
  38. Case "xlsx":
  39. $CI->excel->read_excel2007 ($filePath, $sql, $sheet, $curRow, $riqi, $merge, $mergeCol);
  40. Break
  41. }
  42. $CI->mytool->import_info ("Filepath= $filePath, sql= $sql");
  43. }
  44. /**
  45. * 2012-1-14 Read workbook name (sheetnames)
  46. */
  47. function Read_sheetnames ($filePath) {
  48. $CI = &get_instance ();
  49. $name = $this->_file_extend ($filePath);
  50. $sheetnames;
  51. Switch ($name) {
  52. Case "CSV":
  53. $sheetnames = $CI->excel->read_csv_sheet ($filePath);
  54. Break
  55. Case "XLS":
  56. $sheetnames = $CI->excel->read_2003excel_sheet ($filePath);
  57. Break
  58. Case "xlsx":
  59. $sheetnames = $CI->excel->read_excel2007_sheets ($filePath);
  60. Break
  61. }
  62. return $sheetnames;
  63. }
  64. Read file suffix name
  65. function _file_extend ($file _name) {
  66. $extend =explode (".", $file _name);
  67. $last =count ($extend)-1;
  68. return $extend [$last];
  69. }
  70. -----------------------------------------------ready to keep
  71. 2011-12-21 New CVS export feature
  72. Public Function Export_csv ($filename, $title, $datas, $delim = ",", $newline = "\ n", $enclosure = ' "') {
  73. $CI = &get_instance ();
  74. $cvs = $this->_csv_from_result ($title, $datas, $delim, $newline, $enclosure);
  75. $CI->load->helper (' Download ');
  76. $name =mb_convert_encoding ($filename, "GBK", "UTF-8");
  77. Force_download ($name, $cvs);
  78. }
  79. /**
  80. * @param $titles: Title
  81. * @param $datas: Data
  82. */
  83. function _csv_from_result ($titles, $datas, $delim = ",", $newline = "\ n", $enclosure = ' "') {
  84. $out = ";
  85. First generate the headings from the table column names
  86. foreach ($titles as $name) {
  87. $name =mb_convert_encoding ($name, "GBK", "UTF-8");
  88. $out. = $enclosure. Str_replace ($enclosure, $enclosure. $enclosure, $name). $enclosure. $delim;
  89. }
  90. $out = RTrim ($out);
  91. $out. = $newline;
  92. Next blast through the result array and build out the rows
  93. foreach ($datas as $row)
  94. {
  95. foreach ($row as $item)
  96. {
  97. $item =mb_convert_encoding ($item, "GBK", "UTF-8");
  98. $out. = $enclosure. Str_replace ($enclosure, $enclosure. $enclosure, $item). $enclosure. $delim;
  99. }
  100. $out = RTrim ($out);
  101. $out. = $newline;
  102. }
  103. return $out;
  104. }
  105. }
Copy Code

phpexcel ~ 13KB Download ($)

  1. /**
  2. * Phpexcel
  3. *
  4. * Copyright (C) 2006-2010 Phpexcel
  5. *
  6. * This library was free software; You can redistribute it and/or
  7. * Modify it under the terms of the GNU Lesser general public
  8. * License as published by the Free software Foundation; Either
  9. * Version 2.1 of the License, or (at your option) any later version.
  10. *
  11. * This library was distributed in the hope that it'll be useful,
  12. * but without any WARRANTY; Without even the implied warranty of
  13. * merchantability or FITNESS for A particular PURPOSE. See the GNU
  14. * Lesser general public License for more details.
  15. *
  16. * You should has received a copy of the GNU Lesser general public
  17. * License along with this library; If not, write to the free software
  18. * Foundation, Inc., Wuyi Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  19. *
  20. * @category Phpexcel
  21. * @package Phpexcel
  22. * @copyright Copyright (c) 2006-2010 Phpexcel (Http://www.codeplex.com/PHPExcel)
  23. * @license Http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
  24. * @version 1.7.4, 2010-08-26
  25. */
  26. /** Error Reporting */
  27. Error_reporting (E_all);
  28. Date_default_timezone_set (' Asia/shanghai ');
  29. /** Phpexcel */
  30. Require_once ' classes/phpexcel.php ';
  31. Require_once ' classes/phpexcel/iofactory.php ';
  32. /**
  33. * Output to Excel on the page
  34. */
  35. /**
  36. * Ci_excel
  37. *
  38. * @package CI
  39. * @author Admin
  40. * @copyright 2011
  41. * @version $Id $
  42. * @access Public
  43. */
  44. Class Ci_excel
  45. {
  46. column header, identity on each column of Excel
  47. Private $cellArray = Array (
  48. 1=> ' A ', 2=> ' B ', 3=> ' C ', 4=> ' D ', 5=> ' E ',
  49. 6=> ' F ', 7=> ' G ', 8=> ' H ', 9=> ' I ',10=> ' J ',
  50. 11=> ' K ',12=> ' L ',13=> ' M ',14=> ' N ',15=> ' O ',
  51. 16=> ' P ',17=> ' Q ',18=> ' R ',19=> ' S ',20=> ' T ',
  52. 21=> ' U ',22=> ' V ',23=> ' W ',24=> ' X ',25=> ' Y ',
  53. 26=> ' Z ',
  54. 27=> ' AA ', 28=> ' AB ', 29=> ' AC ', 30=> ' AD ', 31=> ' AE ',
  55. 32=> ' AF ', 33=> ' AG ', 34=> ' AH ', 35=> ' AI ',36=> ' AJ ',
  56. 37=> ' AK ',38=> ' AL ',39=> ' AM ',40=> ' an ',41=> ' AO ',
  57. 42=> ' AP ',43=> ' AQ ',44=> ' AR ',45=> ' as ',46=> ' at ',
  58. 47=> ' AU ',48=> ' AV ',49=> ' AW ',50=> ' AX ',51=> ' AY ',
  59. 52=> ' AZ ', 53=> ' BA ', 54=> ' BB ', 55=> ' BC ', 56=> ' BD ', 57=> ' be ',
  60. 58=> ' BF ', 59=> ' BG ', 60=> ' BH ', 61=> ' BI ', 62=> ' BJ ', 63=> ' BK ', 64=> ' BL ');
  61. Private $E 2003 = ' E2003 ';
  62. Private $E = ' E2007 ';
  63. Private $ECSV = ' ecsv ';
  64. Private $tempName; When the merge file is read, if the second behavior is empty, the name of the first row is taken
  65. /********************************* Export Data Start ****************************************************/
  66. /**
  67. * Generate Excel2007 file
  68. */
  69. function write_excel2007 ($title = ", $data =", $name = ")
  70. {
  71. $objPHPExcel = $this->_excelcomm ($title, $data, $name);
  72. Redirect output to a client ' s Web browser (Excel2007)
  73. Header (' Content-type:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8 ');
  74. Header ("Content-disposition:attachment;filename= $name. xlsx");
  75. Header (' cache-control:max-age=0 ');
  76. $objWriter = Phpexcel_iofactory::createwriter ($objPHPExcel, "Excel2007");
  77. $objWriter->save (' php://output '); Output allows data to be written to the export buffering mechanism in the same way as print () and Echo ().
  78. Exit
  79. }
  80. /**
  81. * Generate Excel2003 file
  82. */
  83. function write_excel2003 ($title = ', $data = ', $name = ') {
  84. $objPHPExcel = $this->_excelcomm ($title, $data, $name);
  85. Redirect output to a client ' s Web browser (EXCEL5)
  86. Header (' Content-type:application/vnd.ms-excel;charset=utf-8 ');
  87. Header ("Content-disposition:attachment;filename= $name. xls");
  88. Header (' cache-control:max-age=0 ');
  89. $objWriter = Phpexcel_iofactory::createwriter ($objPHPExcel, ' Excel5 ');
  90. $objWriter->save (' php://output ');
  91. }
  92. /**
  93. * Generate CSV file
  94. */
  95. function write_csv ($title = ', $data = ', $name = ') {
  96. $objPHPExcel = $this->_excelcomm ($title, $data, $name);
  97. Header ("Content-type:text/csv;charset=utf-8");
  98. Header ("content-disposition:attachment; Filename= $name. csv ");
  99. Header (' cache-control:must-revalidate,post-check=0,pre-check=0 ');
  100. Header (' expires:0 ');
  101. Header (' Pragma:public ');
  102. $objWriter = new Phpexcel_writer_csv ($objPHPExcel, ' CSV ');
  103. $objWriter->save ("Php://output");
  104. Exit
  105. }
  106. function _excelcomm ($title, $data, $name) {
  107. Create New Phpexcel Object
  108. $objPHPExcel = new Phpexcel ();
  109. $objPHPExcel = $this->_writetitle ($title, $objPHPExcel);
  110. $objPHPExcel = $this->_writedatas ($data, $objPHPExcel);
  111. $objPHPExcel = $this->_write_comm ($name, $objPHPExcel);
  112. return $objPHPExcel;
  113. }
  114. Output title
  115. function _writetitle ($title, $objPHPExcel) {
  116. Header Loop (header)
  117. foreach ($title as $tkey = = $tvalue) {
  118. $tkey = $tkey +1;
  119. $cell = $this->cellarray[$tkey]. ' 1 '; The 1th row of column $tkey, the identifier of the column (a). Z
  120. ADD some data//table header
  121. $tvalue =mb_convert_encoding ($tvalue, "UTF-8", "GBK");
  122. $objPHPExcel->setactivesheetindex (0)->setcellvalue ($cell, $tvalue); Set the value of column $row (title)
  123. }
  124. return $objPHPExcel;
  125. }
  126. Output content
  127. function _writedatas ($data, $objPHPExcel) {
  128. Content loops (return values for database queries)
  129. foreach ($data as $key = = $value) {
  130. $i = 1;
  131. The foreach ($value as $mkey + $mvalue) {//return type is array ([0]=>array ()), so here it is to loop its value, that is, the array inside
  132. $rows = $key +2; Start is the second line
  133. $mrow = $this->cellarray[$i]. $rows; Line $row of section $i
  134. $mvalue =mb_convert_encoding ($mvalue, "GBK", "UTF-8");
  135. Print_r ($mrow. " ---> ". $mvalue);
  136. $objPHPExcel->setactivesheetindex (0)->setcellvalueexplicit ($mrow, $mvalue);
  137. $i + +;
  138. }
  139. }
  140. return $objPHPExcel;
  141. }
  142. function _write_comm ($name, $objPHPExcel) {
  143. Rename sheet (title in lower-left corner)
  144. $objPHPExcel->getactivesheet ()->settitle ($name);
  145. Set Active sheet Index to the first sheet, so Excel opens this as the first sheet
  146. $objPHPExcel->setactivesheetindex (0); Default display
  147. return $objPHPExcel;
  148. }
  149. /********************************* Export Data End ****************************************************/
  150. /********************************* Read Data start ****************************************************/
  151. /**
  152. * Method of Use, $INSERTSQL: Insert XX (x1,x2,x3,x4) value (
  153. */
  154. function _comm_insert ($objReader, $filePath, $INSERTSQL, $sheet =2, $curRow =2, $riqi =true) {
  155. function _comm_insert ($objPHPExcel, $INSERTSQL, $curRow, $merge =false, $mergeCol = ' B ') {
  156. $CI = &get_instance ();
  157. $currentSheet = $objPHPExcel->getsheet ();//Get the specified activation
  158. How many columns does the/** get altogether? *
  159. $allColumn = $currentSheet->gethighestcolumn ();
  160. How many lines does the/** get altogether? */
  161. $allRow = $currentSheet->gethighestrow ();
  162. $size =strlen ($allColumn);//If the z is exceeded, no execution occurs
  163. $esql = "";
  164. for ($currentRow = $curRow; $currentRow <= $allRow; $currentRow + +) {
  165. $sql = $INSERTSQL;
  166. if ($size ==2) {
  167. $i = 1;
  168. $currentColumn = ' A ';
  169. while ($i <= 26) {
  170. $address = $currentColumn. $currentRow;
  171. $temp = $currentSheet->getcell ($address)->getcalculatedvalue ();
  172. $sql. = ' "'. $temp. '". ",";
  173. $currentColumn + +;
  174. $i + +;
  175. }
  176. for ($currentColumn = ' AA '; $currentColumn <= $allColumn; $currentColumn + +) {
  177. $address = $currentColumn. $currentRow;
  178. $sql. = ' "'. $currentSheet->getcell ($address)->getcalculatedvalue (). '". ",";
  179. }
  180. }else{
  181. for ($currentColumn = ' A '; $currentColumn <= $allColumn; $currentColumn + +) {
  182. if ($merge) {//If the value of the merge is read, it is determined that if the value of this row is null, the preceding tempname is assigned to $temp;
  183. if ($currentColumn = = $mergeCol) {//Here first specifies that the merged values begin reading from the first name of column B. Later encountered different re-adjustments.
  184. $temp = $currentSheet->getcell ($mergeCol. $currentRow)->getcalculatedvalue ();
  185. if (empty ($temp)) {
  186. $temp = $this->tempname;
  187. }else{
  188. $this->tempname= $temp;
  189. }
  190. }else{
  191. $address = $currentColumn. $currentRow;//getvalue ()
  192. $temp = $currentSheet->getcell ($address)->getcalculatedvalue ();
  193. }
  194. }else{
  195. $address = $currentColumn. $currentRow;//getvalue ()
  196. $temp = $currentSheet->getcell ($address)->getcalculatedvalue ();
  197. }
  198. $sql = $sql. ' ". $temp. ' ".", ";
  199. }
  200. }
  201. $esql =rtrim ($sql, ","). ') ';
  202. Echo ($esql);
  203. Return
  204. $CI->db->simple_query ($esql);
  205. }
  206. }
  207. /**
  208. * $filePath: Read the path to the file
  209. * $INSERTSQL: Spelled sql
  210. */
  211. function read_excel2007 ($filePath, $INSERTSQL, $sheet =0, $curRow =2, $riqi =true, $merge =false, $mergeCol = "B") {
  212. $OBJS = $this->_get_phpexcel ($this->e2007, $filePath, $sheet, $INSERTSQL, $riqi);
  213. $this->_comm_insert ($objs ["EXCEL"], $objs ["SQL"], $curRow, $merge, $mergeCol);
  214. }
  215. /**
  216. * Read 2003Excel
  217. */
  218. function Read_2003excel ($filePath, $INSERTSQL, $sheet =0, $curRow =2, $riqi =true, $merge =false, $mergeCol = "B") {
  219. $OBJS = $this->_get_phpexcel ($this->e2003, $filePath, $sheet, $INSERTSQL, $riqi);
  220. $this->_comm_insert ($objs ["EXCEL"], $objs ["SQL"], $curRow, $merge, $mergeCol);
  221. }
  222. /**
  223. * Read CSV
  224. */
  225. function Read_csv ($filePath, $INSERTSQL, $sheet =0, $curRow =2, $riqi =true, $merge =false, $mergeCol = "B") {
  226. $OBJS = $this->_get_phpexcel ($this->ecsv, $filePath, $sheet, $INSERTSQL, $riqi, $mergeCol);
  227. $this->_comm_insert ($objs ["EXCEL"], $objs ["SQL"], $curRow, $merge);
  228. }
  229. --------------------------------Start reading workbook information
  230. /**
  231. * Read Excel2007 workbook name
  232. */
  233. function Read_excel2007_sheets ($filePath) {
  234. return $this->_get_sheetnames ($this->e2007, $filePath);
  235. }
  236. /**
  237. * Read 2003Excel workbook name
  238. */
  239. function Read_2003excel_sheet ($filePath) {
  240. return $this->_get_sheetnames ($this->e2003, $filePath);
  241. }
  242. /**
  243. * Read the CSV workbook name
  244. */
  245. function Read_csv_sheet ($filePath) {
  246. return $this->_get_sheetnames ($this->ecsv, $filePath);
  247. }
  248. --------------------------------End of Reading workbook information
  249. /**
  250. * 2012-1-14--------------------------
  251. */
  252. Read Reader stream
  253. function _get_reader ($name) {
  254. $reader =null;
  255. Switch ($name) {
  256. Case $this->e2003:
  257. $reader = new Phpexcel_reader_excel5 ();
  258. Break
  259. Case $this->e2007:
  260. $reader = new phpexcel_reader_excel2007 ();
  261. Break
  262. Case $this->ecsv:
  263. $reader = new Phpexcel_reader_csv ();
  264. Break
  265. }
  266. return $reader;
  267. }
  268. Get the $objphpexcel file object
  269. function _get_phpexcel ($name, $filePath, $sheet, $INSERTSQL, $riqi) {
  270. $reader = $this->_get_reader ($name);
  271. $PHPExcel = $this->_init_excel ($reader, $filePath, $sheet);
  272. if ($riqi) {//If no date is required, then ignore.
  273. $INSERTSQL = $insertSql. ' ". $reader->getsheettitle (). ' "'.", ";//first field fixed is date 2012-1-9
  274. }
  275. Return Array ("EXCEL" = $PHPExcel, "SQL" = = $INSERTSQL);
  276. }
  277. Get the name of the work book
  278. function _get_sheetnames ($name, $filePath) {
  279. $reader = $this->_get_reader ($name);
  280. $this->_init_excel ($reader, $filePath);
  281. return $reader->getallsheets ();
  282. }
  283. Loading files
  284. function _init_excel ($objReader, $filePath, $sheet = ") {
  285. $objReader->setreaddataonly (TRUE);
  286. if (!empty ($sheet)) {
  287. $objReader->setsheetindex ($sheet);//Read the first few sheet.
  288. }
  289. return $objReader->load ("$filePath");
  290. }
  291. -------------------------------2012-1-14
  292. }
  293. /********************************* Read Data End ****************************************************/
Copy Code

[PHP] Code

  1. ------------------------the import Operation------------------------
  2. /**
  3. * $sql = "INSERT into". Mymsg::wy_mmb. " (dizhi,xingming) VALUES (";
  4. */
  5. Upload and read files first
  6. function Upbyfile ($sql, $url, $curRow = 2, $RIQI = true, $merge = FALSE, $mergeCol = ' B ')
  7. {
  8. $CI = &get_instance ();
  9. $config [' allowed_types '] = ' * '; All documents are allowed
  10. $config [' upload_path '] = IMPORT; Only the path of the file
  11. $CI->load->library (' upload ', $config);
  12. if ($CI->upload->do_upload ()) {//default name is: UserFile
  13. $data = $CI->upload->data ();
  14. $full _name = $data [' Full_path ']; Get the Saved path
  15. $full _name = mb_convert_encoding ($full _name, "GBK", "UTF-8");
  16. $sheet = $CI->input->post ("sheet"); Read Column x Chart
  17. if (empty ($sheet)) {
  18. $sheet = 0;
  19. }
  20. $CI->read_write->read_facotry ($full _name, $sql, $sheet, $curRow, $RIQI, $merge, $mergeCol); Execute Insert Command
  21. }
  22. $this->alert_msg (mymsg::import_success, Site_url ($url));
  23. }
  24. ------------------------------the export Operation----------------------------------
  25. Export the specified table field
  26. Public Function Show_export () {
  27. -----database Fields
  28. $field =implode (",", $this->input->post ("Listcheckbox_show"));//Database field
  29. Display Name
  30. $titleArray = $this->input->post ("Listcheckbox_field");//Field name displayed (field comment Note name, because there are some empty arrays passed in, so must be filtered)
  31. $title =array ();
  32. foreach ($titleArray as $key = = $value) {
  33. if (!empty ($value)) {
  34. $title []= $value;
  35. }
  36. }
  37. ---database table name
  38. $table = $this->input->post ("TableName");
  39. --database table name (Comment comment)
  40. $show _name= $this->input->post ("tablecomment");
  41. --Export type
  42. $type = $this->input->post ("type");
  43. --where Month
  44. $y _month= $this->input->post ("Year_month");
  45. if (!empty ($y _month)) {
  46. $where ["Riqi"]= $y _month;
  47. $datas = $this->mcom_model->querybywhererefield ($field, $where, $table);
  48. }else{
  49. --Write the data
  50. $datas = $this->mcom_model->querybyfield ($field, $table);
  51. }
  52. ---start exporting
  53. $this->read_write->write_factory ($title, $datas, $show _name, $type);
  54. }
Copy Code

PHP, Phpexcel
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.