首頁  >  文章  >  後端開發  >  php 使用PHPEXcel匯出表格數據

php 使用PHPEXcel匯出表格數據

WBOY
WBOY原創
2016-07-25 08:41:591401瀏覽

專案中需要將表格中的資料匯出,網路上找了找發現phpexcel蠻好用的.特此分享

PHPEXCEL

  1. if(!defined('BASEPATH')) exit('No direct script access allowed');//物資發料>//物資發料單明細
  2. class Read_write{
  3. /**
  4. * $name:選擇的類型(CSV,EXCEL2003,2007)
  5. * $titles:標題數組
  6. * $querys:查詢傳回的陣列$query->result_array();
  7. * $ filename:儲存的檔案名稱
  8. */
  9. function write_Factory($titles,$querys,$filename,$name="EXCEL2003"){
  10. $CI = &get_instance();
  11. $filename=mb_convert_encoding($filename, "GBK","UTF-8");
  12. switch ($name) {
  13. case "CSV":
  14. $CI->excel->write_CSV($titles,$querys,$filename);
  15. break;
  16. case "EXCEL2003":
  17. $CI->excel->write_EXCEL2003($titles,$querys, $filename);
  18. break;
  19. case "EXCEL2007":
  20. $CI->excel->write_EXCEL2007($titles,$querys,$filename);
  21. break;
  22. }
  23. }
  24. /**
  25. * $名稱:
  26. */
  27. function read_Facotry($filePath,$sql,$sheet=0,$curRow=2,$riqi=TRUE,$merge=FALSE,$mergeCol ="B"){
  28. $CI = &get_instance();
  29. $name=$this->_file_extend($filePath);
  30. switch ($name) {
  31. case "csv":
  32. $CI->excel->read_CSV($filePath,$sql,$sheet,$curRow,$riqi,$merge,$mergeCol);
  33. break;
  34. case "xls":
  35. $ CI->excel->read_2003Excel($filePath,$sql,$sheet,$curRow,$riqi,$merge,$mergeCol);
  36. break;
  37. case "xlsx":
  38. $CI-> excel->read_EXCEL2007($filePath,$sql,$sheet,$curRow,$riqi,$merge,$mergeCol);
  39. break;
  40. }
  41. $CI->mytool->import_info("filePath =$filePath,sql=$sql");
  42. }
  43. /**
  44. * 2012-1-14 讀取工作薄名稱(sheetnames)
  45. */
  46. function read_sheetNames($filePath){
  47. $CI = &get_instance();
  48. $ name=$this->_file_extend($filePath);
  49. $sheetnames;
  50. switch ($name) {
  51. case "csv":
  52. $sheetnames=$CI->excel->read_CSV_Sheet( $filePath);
  53. break;
  54. case "xls":
  55. $sheetnames=$CI->excel->read_2003Excel_Sheet($filePath);
  56. break;
  57. case "xlsx"
  58. $sheetnames=$CI->excel->read_EXCEL2007_Sheets($filePath);
  59. break;
  60. }
  61. return $sheetnames;
  62. }
  63. //讀取檔案後綴名
  64. function _file_extend($file_name){
  65. $extend =explode("." , $file_name);
  66. $last=count($extend)-1;
  67. return $extend[$last];
  68. }
  69. //-------------------------------------------------- -----預備保留
  70. //2011-12-21新增CVS匯出功能
  71. public function export_csv($filename,$title,$datas, $delim = ",", $newline = "n ", $enclosure = '"'){
  72. $CI = &get_instance();
  73. $cvs= $this->_csv_from_result($title,$datas,$delim,$newline,$enclosure);
  74. $CI->load->helper('download');
  75. $name=mb_convert_encoding($filename, "GBK","UTF-8");
  76. force_download($name, $cvs);
  77. }
  78. /**
  79. * @param $titles:標題
  80. * @param $datas:資料
  81. */
  82. function _csv_from_result($titles,$datas, $delim = ",", $newline = "n", $enclosure = '"'){
  83. $out = '';
  84. // First generate the headings from the table column names
  85. foreach ($titles as $name){
  86. $name=mb_convert_encoding($name, "GBK","UTF -8");
  87. $out .= $enclosure.str_replace($enclosure, $enclosure.$enclosure, $name).$enclosure.$delim;
  88. }
  89. $out = rtrimim;
  90. }
  91. $out = rtrim ($out);
  92. $out .= $newline;
  93. // Next blast through the result array and build out the rows
  94. foreach ($datas as $row)
  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. }
}
複製程式碼

PHPEXCEL ~ 13KB    下載(28)

  1. /**
  2. * PHPExcel
  3. *
  4. * 版權所有(C) 2006 - 2010 PHPExcel
  5. *
  6. * 該函式庫是免費軟體;您可以重新散佈它和/或
  7. * 根據GNU Lesser General Public 的條款修改它
  8. * 由自由軟體基金會發布的授權;
  9. * 授權的2.1 版,或(由您選擇)任何更高版本。
  10. *
  11. * 分發此程式庫的目的是希望它有用,
  12. * 但不提供任何保證;甚至沒有默示保證
  13. *適銷性或特定用途的適用性。 請參閱 GNU
  14. * 較小通用公共授權以了解更多詳細資訊。
  15. *
  16. * 您應該已收到GNU 小通用公共許可證
  17. * 與此庫一起的許可證;如果沒有,請寫信給自由軟體
  18. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  19. *
  20. * @category PHPExcel
  21. * @package PHPExcel
  22. * @copyright 版權所有(c) 2006 - 2010 cel /www.codeplex.com/PHPExcel)
  23. * @license http://www.gnu.org/licenses/old-licenses/lgpl- 2.1.txt LGPL
  24. * @版本1.7.4, 2010-08 -26
  25. */
  26. /**錯誤報告*/
  27. error_reporting(E_ALL);
  28. date_default_timezone_set('預設/預設');
  29. /**PHPExcel*/
  30. require_once 'Classes/PHPExcel.php';
  31. require_once 'Classes/PHPExcel/IOy.';
  32. require_once 'Classes/PHPExcel/IOy.';
  33. require_once 'Classes/PHPExcel/IOy.';
  34. require_once 'Classes/PHPExcel/IOy.';
  35. require_once 'Classes/PHPExcel/IOy.'PExcel/IOphp;
  36. /**
  37. * 輸出到頁面上的EXCEL
  38. */
  39. /**
  40. * CI_Excel
  41. *
  42. * @package ci
  43. * @author admin
  44. * @copyright 2011
  45. * @version $Id$
  46. * @access public
  47. * @version $Id$
  48. * @access public
  49. * @version $Id$
  50. * @access public
  51. * @version $Id$
  52. * @access public
  53. * @version $Id$
  54. * @access public
  55. */
  56. class CI_Excel
  57. {
  58. //指定,ExcelOriginalSpecification
  59. private $ cellArray = array (
  60. 1=>'A', 2=>'B', 3=>'C', 4=>'D', 5=>'E',
  61. 6=>'F ', 7=>' G', 8=>'H', 9=>'I',10=>'J',
  62. 11=>'K',12=>'L',13=>'M',14= >'N',15=>'O',
  63. 16=>'P',17=>'Q',18=>'R',19=>'S',2 =>'T',
  64. 21=>'U',22=>'V',23=>'W',24=>'X',25=>'Y',
  65. 26=>'Z',
  66. 27=>'AA', 28=>'AB', 29=>'AC', 30=>'AD', 31=>'AE',
  67. 32=>'AF', 33=>' AG', 34=>'啊', 35=>'AI',36=>'AJ',
  68. 37=>'AK',38=>'AL',39=>'AM',40= >'AN',41=>'AO',
  69. 42=>'AP',43=>'AQ',44=>'AR',45=>'AS',4 =>'AT',
  70. 47=>'AU',48=>'AV',49=>'是',50=>'AX',51=>'否',
  71. 52 => 'AZ', 53= >'BA', 54=>'BB', 55=>'BC', 56=>'BD', 57=>'BE',
  72. 58=>'BF', =>'BG', 60 =>'BH', 61=>'BI', 62=>'BJ', 63=>'BK', 64=>'BL'); E2003';
  73. private $E2007 = 'E2007';
  74. 私人$ECSV = 'ECSV';
  75. 私人$tempName; //指定特定類型,產生預設值,產生預設值
  76. /*********************************匯出資料開始**************** ************************************/
  77. /** * 產生Excel2007檔案*/ function write_EXCEL20 07( $title=' ',$data ='',$name='') { $objPHPExcel=$this->_excelComm($title,$data='',$name); //將Application基於網頁設計器(Excel 2007) header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8'); 版面: Open;filename=$name.xlsx") ; header('Cache-Control: max-age=0'); ") ; $objWriter->save('php://output'); //output 是 print() 和 echo() 方法的預設值。
  78. exit;
  79. }
  80. /**
  81. * 產生Excel2003檔
  82. */
  83. function write_EXCEL2003($title='',$data='',$name=''){
  84. $objPHPExcel=$this->_excelComm($title,$data,$name);
  85. // 將輸出重新導向到客戶端的Web 瀏覽器(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. /**
  94. * 產生CSV檔
  95. */
  96. function write_CSV($title='',$data='',$name=''){
  97. $objPHPExcel=$this->_excelComm($title ,$data,$name);
  98. header("Content-Type: text/csv;charset=UTF-8");
  99. header("內容處置:附件;檔案名稱=$name. csv");
  100. header('Cache-Control:必須重新驗證,post-check=0,pre-check=0');
  101. header('過期時間:0');
  102. header( 'Pragma:public');
  103. $objWriter = new PHPExcel_Writer_CSV($objPHPExcel,'CSV');
  104. $objWriter->save("php://output");
  105. exit;
  106. function _excelComm($title,$data,$name){
  107. // 建立新的PHPExcel 物件
  108. $objPHPExcel = new PHPExcel();
  109. $objPHPExcel=$this- >_writeTitle($title, $objPHPExcel);
  110. $objPHPExcel=$this->_writeDatas($data,$objPHPExcel);
  111. $objPHPExcel=$this->_write_comm($name,$objPHPexcel); > return $objPHPExcel ;
  112. }
  113. // 輸出標題
  114. function _writeTitle($title,$objPHPExcel){
  115. //表頭循環(標題) $tkey = $tkey 1;
  116. $cell = $this->cellArray[$tkey].'1'; //第$tkey欄的第1行,列的識別碼(a..z)
  117. // 增加一些資料//表頭
  118. // $tvalue=mb_convert_encoding($tvalue, "UTF-8 ","GBK");
  119. $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cell, $tvalue); //設定第$row列的值(標題)
  120. }
  121. return $objPHPExcel;
  122. }
  123. / /輸出內容
  124. function _writeDatas($data,$objPHPExcel){
  125. //內容循環(資料庫查詢的回傳值)
  126. foreach($data as $key =>$value) {
  127. $ i = 1;
  128. foreach ($value as $mkey =>$ mvalue){ //回傳的型別是array([0]=>array());,所以這裡要循環它的值,如果裡面的array
  129. $rows = $key 2; //開始是第二行
  130. $mrow = $this->cellArray[$i].$rows; //第$i列的第$row行
  131. // $mvalue=mb_convert_encoding($mvalue, "GBK","UTF-8");
  132. // print_r($mrow."---> ;".$mvalue);
  133. $objPHPExcel->setActiveSheetIndex(0)->setCellValueExplicit($mrow, $mvalue);
  134. $i ;
  135. }
  136. }
  137. return $objPHPHPExcel>; function _write_comm($name,$objPHPExcel){
  138. // 重新命名sheet(左下角的標題)
  139. // $objPHPExcel->getActiveSheet()->setTitle($name);
  140. // 將活動工作表索引設定為第一個工作表,因此Excel 將其作為第一個工作表開啟
  141. $objPHPExcel->setActiveSheetIndex(0 ); // 預設顯示
  142. return $objPHPExcel;
  143. }
  144. /*********************************匯出資料結束**************** ************************************/
  145. /*********************************讀取資料開始****************** *************************************/
  146. /**
  147. * 使用方法,$insertSql:insert xx (x1,x2,x3,x4) value (
  148. */
  149. // 函數_comm_insert($objReader , $filePath,$insertSql,$sheet=2,$curRow=2,$riqi=TRUE){
  150. 函數_comm_insert($objPHPExcel,$insertSql,$curRow,$merge=FALSE,$mergeCol='B' ) {
  151. $CI = &get_instance();
  152. $currentSheet = $objPHPExcel->getSheet();//取得指定的啟動
  153. /**取得一共有多少列*/
  154. $allColumn = $ currentSheet ->getHighestColumn();
  155. /**取得一共有多少行*/
  156. $allRow = $currentSheet->getHighestRow();
  157. $size=strlen($allColumn);//如果超出Z,則出現不執行下去
  158. $esql="";
  159. for($currentRow = $curRow;$currentRow $sql=$insertSql;
  160. if($size==2){
  161. $i=1;
  162. $currentColumn='A';
  163. while ($i $address = $currentColumn.$currentRow;
  164. $temp=$currentSheet->getCell($address)->getCalculatedValue();
  165. $sql. ='"'.$temp.'"'.",";
  166. $currentColumn ;
  167. $i ;
  168. }
  169. for($currentColumn='AA';$currentColumn $address = $currentColumn.$currentRow;
  170. $sql.='"'.$currentSheet->getCell($address)->getCalculatedValue().'"'." ," ;
  171. }
  172. }else{
  173. for($currentColumn='A';$currentColumn if($merge){//如果是$currentColumn ){
  174. if($merge){//如果是讀取合併的值,則判斷,如果此行的值為NULL,則把前面的tempName賦值給$temp; if($currentColumn==$mergeCol){//這裡先指定從B列的名稱開始讀取合併的值。
  175. $temp=$currentSheet->getCell($mergeCol.$currentRow)->getCalculatedValue();
  176. if(empty($temp)){
  177. $temp=$this->tempName ;
  178. }else{
  179. $this->tempName=$temp;
  180. }
  181. }else{
  182. $address = $currentColumn.$currentRow;//getValue()
  183. $temp=$ currentSheet->getCell($address)->getCalculatedValue();
  184. }
  185. }else{
  186. $address = $currentColumn.$currentRow;//getValue()
  187. $temp=$currentSheet->getCell($address)->getCalculated();
  188. }
  189. $sql=$sql.'"'.$temp.'"'.",";
  190. }
  191. }
  192. $esql=rtrim($sql,"," ).')';
  193. //echo($esql);
  194. //return;
  195. $CI->db->simple_query($esql);
  196. }
  197. }
  198. }
  199. /**
  200. * $filePath:讀取檔案的路徑
  201. * $insertSql:拼字的SQL
  202. */
  203. function read_EXCEL2007($filePath,$insertSql,$sheet=0,$curRow=2,$riqi=TRUE,$merge=FALSE,$mergeCol="B") {
  204. $objs=$this->_get_PHPExcel($this->E2007,$filePath,$sheet,$insertSql,$riqi);
  205. $this->_comm_insert($objs["EXCEL" ],$objs[ "SQL"],$curRow,$merge,$mergeCol);
  206. }
  207. /**
  208. * 讀取2003Excel
  209. */
  210. function read_2003Excel($filePath,$insertSql,$sheet=0,$curRow=2,$riqi=TRUE,$merge=FALSE,$merge= "B"){
  211. $objs=$this->_get_PHPExcel($this->E2003,$filePath,$sheet,$insertSql,$riqi);
  212. $this->_comm_insert($objs ["EXCEL "],$objs["SQL"],$curRow,$merge,$mergeCol);
  213. }
  214. /**
  215. * 讀取CSV
  216. */
  217. function read_CSV($filePath,$insertSql,$sheet=0,$curRow=2,$riqi=TRUE,$merge=FALSE,$merge= "B"){
  218. $objs=$this->_get_PHPExcel($this->ECSV,$filePath,$sheet,$insertSql,$riqi,$mergeCol);
  219. $this->_comm_insert ($objs ["EXCEL"],$objs["SQL"],$curRow,$merge);
  220. }
  221. //--------------------------------讀取工作薄資訊開始
  222. /**
  223. * 讀取Excel2007工作薄名
  224. */
  225. function read_EXCEL2007_Sheets($filePath){
  226. return $this->_get_sheetnames($this->E2007,$filePath);
  227. }
  228. }
  229. * 讀取2003Excel工作薄名稱
  230. */
  231. function read_2003Excel_Sheet($filePath){
  232. return $this->_get_sheetnames($this->E2003,$filePath);
  233. }
  234. /**>🎝> /
  235. function read_CSV_Sheet($filePath){
  236. return $this->_get_sheetnames($this->ECSV,$filePath);
  237. }
  238. //---- ------ ----------------------讀取工作薄資訊結束
  239. /**
  240. * 讀取CSV工作薄名稱
  241. */
  242. //讀取Reader流
  243. function _get_Reader($name){
  244. $reader=null;
  245. switch ($name) {
  246. case $this->E2003:
  247. $reader = new PHPExcel_Reader_Excel5 (); 案例$this->E2007:
  248. $reader = new PHPExcel_Reader_Excel2007();
  249. 中斷;
  250. 案例$this->ECSV:
  251. $ reader = new🎜> 案例$this->ECSV:
  252. $ reader = new PHPcm. > break;
  253. }
  254. return $reader;
  255. }
  256. //取得$objPHPExcel檔案物件
  257. function _get_PHPExcel($name,$filePath,$sheet,$insertSql,$riqi){
  258. $reader=$this->_get_Reader($name);
  259. $PHPExcel= $this->_init_Excel($reader,$filePath,$sheet);
  260. if($riqi){ //如果不需要日期,則忽略。
  261. }
  262. return array("EXCEL"=>$PHPExcel,"SQL"=>$insertSql);
  263. }
  264. //取得工作薄名稱
  265. function _get_sheetnames($名稱,$filePath){
  266. $reader=$this->_get_Reader($name);
  267. $this->_init_Excel($reader, $filePath);
  268. return $reader->getAllSheets();
  269. }
  270. //載入檔案
  271. function _init_Excel($objReader,$filePath,$sheet=''){
  272. $objReader->setReadDataOnly(true);
  273. if(!empty( $sheet)){
  274. $objReader->setSheetIndex($sheet);//讀取第幾個Sheet。
  275. }
  276. return $objReader->load("$filePath");
  277. }
  278. //--------------------- ----------2012-1-14
  279. }
  280. /*********************************讀取資料結束****************** *************************************/
複製程式碼

[PHP]代碼

  1. ------------------------導入操作------------ ------------
  2. /**
  3. * $sql="INSERT INTO ".mymsg::WY_MMB." (dizhi,xingming) VALUES (";
  4. */
  5. //先上傳再讀取檔案
  6. function upByFile($sql, $url, $curRow = 2 , $RIQI = true,$merge = FALSE,$mergeCol='B')
  7. {
  8. $CI = &get_instance();
  9. $config['allowed_types'] = '*'; //充許可所有檔案
  10. $config['upload_path'] = IMPORT; // 只在檔案的路徑
  11. $CI->load->library('upload', $config);
  12. if ($CI->upload->do_upload()) { //預設名稱是:userfile
  13. $data = $CI->upload->data();
  14. $full_name = $ data['full_path']; //得到儲存後的路徑
  15. $full_name = mb_convert_encoding($full_name, "GBK", "UTF-8");
  16. $sheet = $CI->input->post ("sheet"); //讀取第x列圖表
  17. if (empty($sheet)) {
  18. $sheet = 0;
  19. }
  20. $CI->read_write- >read_Facotry($full_name, $sql, $sheet, $curRow, $RIQI,$merge,$mergeCol); //執行插入指令
  21. }
  22. $this->alert_msg(mymsg ::IMPORT_SUCCESS, site_url($url));
  23. }
  24. ----------------------------- -匯出操作----------------------------------
  25. //匯出指定的表格欄位
  26. public function show_export(){
  27. //-----資料庫欄位
  28. $field=implode(",",$this->input->post("listCheckBox_show"));//資料庫欄位
  29. //顯示名稱
  30. $titleArray=$this->input->post("listCheckBox_field");//顯示的欄位名稱(欄位Comment註解名稱,因為傳進來的有些空數組,所以必須過濾)
  31. $title=array();
  32. foreach ($titleArray as $key => $value) {
  33. if (!empty($value)) {
  34. $title[]=$value;
  35. }
  36. }
  37. //---資料庫表名
  38. $table=$this->input->post("tableName");
  39. //--資料庫表名稱( Comment註解)
  40. $show_name=$this->input->post("tableComment");
  41. //--匯出型別
  42. $type=$this->input->post("type" );
  43. //--where 年月
  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. //--寫出的資料
  50. $datas=$this->mcom_model->queryByField($field,$table);
  51. }
  52. //---開始匯出
  53. $this-> read_write->write_Factory($title,$datas,$show_name,$type);
  54. }
複製程式碼

php, PHPEXcel


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn