Home  >  Article  >  Backend Development  >  Sample code for phpexcel to import excel data

Sample code for phpexcel to import excel data

WBOY
WBOYOriginal
2016-07-25 08:55:23727browse
  1. /**

  2. * Import basic product information
  3. * edit: bbs.it-home.org
  4. */
  5. public function importProductBasicInfo($data){
  6. include_once 'PHPExcel.php';
  7. include_once 'PHPExcel/IOFactory.php';
  8. include_once 'PHPExcel/Reader/Excel5.php';
  9. //Define an error collection.
  10. $error = array();
  11. $resultInfo = null;
  12. $needNext = true;
  13. //Upload files to the specified location on the server
  14. $ fileName = $_FILES["productinfo"]['name'];
  15. $filePath = CBase_Common_UploadPicture::uploadFile($data["productinfo"], 'product');
  16. //If the file is uploaded successfully, execute the import excel operation
  17. if($filePath == 1) {
  18. $error[1] = "The uploaded file exceeds the value limited by the upload_max_filesize option in php.ini";
  19. }else if($filePath == 4){
  20. $error[ 4] = "No file was uploaded";
  21. }else{
  22. $objReader = PHPExcel_IOFactory::createReader('Excel5');
  23. $objReader->setReadDataOnly(true);
  24. $objPHPExcel = $objReader->load( $filePath);
  25. $objWorksheet = $objPHPExcel->getActiveSheet();
  26. $highestRow = $objWorksheet->getHighestRow();
  27. $highestColumn = $objWorksheet->getHighestColumn();
  28. $highestColumnIndex = PHPExcel_Cell:: columnIndexFromString($highestColumn);
  29. $colums = array();
  30. $data = array();
  31. $excelAllId = array();
  32. $excelIdRow = array();
  33. $execlAllShopLinkedId = array();
  34. for($ i=0;$i<$highestColumnIndex;$i++){
  35. $cValue = trim($objWorksheet->getCellByColumnAndRow($i,1)->getValue());
  36. switch ($cValue) {
  37. case self ::PRODUCT_SAP_CODE : $colums[$i] = "sap_code"; break;
  38. case self::PRODUCT_NAME : $colums[$i] = "pname"; break;
  39. case self::PRODUCT_GROUP : $colums[$i] = "product_group"; break;
  40. case self::PRODUCT_BRAND : $colums[$i] = 'product_brand'; break;
  41. case self::PRODUCT_PROXY_FLAG : $colums[$i] = "product_proxy_flag"; break;
  42. case self ::PRODUCT_BINNING : $colums[$i] = "product_binning"; break;
  43. case self::PRODUCT_SELL_PICK : $colums[$i] = "product_sell_pick"; break;
  44. case self::PRODUCT_ATTRIBUTE : $colums[$i] = "product_attribute"; break;
  45. case self::PRODUCT_SUPPLIER_CODE : $colums[$i] = "vendor_code"; break;
  46. case self::PRODUCT_SUPPLY_ADDRESS : $colums[$i] = "zzwerk_code"; break;
  47. case self ::PRODUCT_BATCH : $colums[$i] = "zzlgort_code"; break;
  48. default : $error[3][] = $cValue; break;
  49. }
  50. }
  51. //Detect whether basic information in Excel exists
  52. $ dataCount = $highestRow - 1;
  53. if(count($colums) == 0) {
  54. $error[5] = "No header";
  55. }
  56. else if(!in_array('sap_code',$colums)) {
  57. $error[2] = "The product SAP code in the header does not exist";
  58. }
  59. else if($dataCount <= 0){
  60. $error[6] = "There is no data in the Excel file";
  61. }
  62. else if(count($error)==0){
  63. for ($i=2;$i<=$highestRow;$i++){
  64. $colkey = array_search('sap_code');
  65. $shopLinkedIdValue = trim( $objWorksheet->getCellByColumnAndRow($colkey,$i)->getValue());
  66. if(!$shopLinkedIdValue) {
  67. continue;
  68. }
  69. if(in_array($shopLinkedIdValue,$execlAllShopLinkedId)){
  70. $error [7][$shopLinkedIdValue]['duplicate'] = true;
  71. $error[7][$shopLinkedIdValue]['excelRow'][] = $i;
  72. $execlAllShopLinkedId[$i] = $shopLinkedIdValue;
  73. $error [7][$shopLinkedIdValue]['noId'] = true;
  74. }else {
  75. $excelIdRow[$shopLinkedIdValue] = $i;
  76. $execlAllShopLinkedId[$i] = $shopLinkedIdValue;
  77. }
  78. }
  79. $dealMultiple = ceil($dataCount / 1000);
  80. $allProduct = array();
  81. for($i=0;$i<$dealMultiple;$i++){
  82. $offset = $i*1000+2;
  83. $max = ($i+1)*1000+1;
  84. $max = ($max > $dataCount) ? $highestRow : $max;
  85. $allShopLinkedId = array();
  86. for($j=$offset; $j<=$max;$j++){
  87. if($execlAllShopLinkedId[$j]){
  88. $allShopLinkedId[] = $execlAllShopLinkedId[$j];
  89. }
  90. }
  91. // Query in the library based on SAP product code The number of records.
  92. $dbShopProducts = $this->getShopLinkedByIds($allShopLinkedId);

  93. for($j=$offset;$j<=$max;$j++){

  94. $ product = array();
  95. for($k=0;$k<$highestColumnIndex;$k++){
  96. $tempV = trim($objWorksheet->getCellByColumnAndRow($k,$j)->getValue()) ;
  97. if($tempV && $tempV != '') {
  98. $product[$colums[$k]] = $tempV;
  99. }
  100. }
  101. //Get the SAP encoding in the file
  102. $id = $product[ 'sap_code'];
  103. if(!$id){
  104. continue;
  105. }
  106. //Check whether the product SAP code already exists
  107. if(!in_array($id,$dbShopProducts)){
  108. $allProduct[$id] = $product;
  109. }else{
  110. $error[7][$id]['hasId'] = true;
  111. }
  112. //Whether the product name is empty
  113. if(!isset($product['pname'])) {
  114. $error[7][$id]['emptyName'] = true;
  115. }
  116. //Whether the product category (product group) is empty
  117. if(!isset($product['product_group'])){
  118. $error[7][$id]['emptyProductGroup'] = true;
  119. }
  120. //Whether the product level (brand) is empty
  121. if(!isset($product['product_brand'])){
  122. $error [7][$id]['emptyProductBrand'] = true;
  123. }
  124. //Whether the proxy sales flag is empty
  125. if(!isset($product['product_proxy_flag'])){
  126. $error[7][$ id]['emptyProductProxyFlag'] = true;
  127. }
  128. //Whether the packing list is empty
  129. if(!isset($product['product_binning'])){
  130. $error[7][$id]['emptyProductBinning '] = true;
  131. }
  132. //Whether the sell first, buy later indicator is empty
  133. if(!isset($product['product_sell_pick'])){
  134. $error[7][$id]['emptyProductSellPick'] = true;
  135. }
  136. //Whether the product attribute is empty
  137. if(!isset($product['product_attribute'])){
  138. $error[7][$id]['emptyProductAttribute'] = true;
  139. }
  140. / /Whether the supplier code is empty
  141. if(!isset($product['vendor_code'])){
  142. $error[7][$id]['emptyVendorCode'] = true;
  143. }
  144. //Whether the supply location is Empty
  145. if(!isset($product['zzwerk_code'])){
  146. $error[7][$id]['emptyZzwerkCode'] = true;
  147. }
  148. //Whether the library area is empty
  149. if(!isset ($product['zzlgort_code'])){
  150. $error[7][$id]['emptyZzlgortCode'] = true;
  151. }
  152. if(isset($error[7][$id])){
  153. $ error[7][$id]['excelRow'] = $j;
  154. }
  155. }
  156. }
  157. }
  158. }
  159. $resultInfo['fileName'] = $fileName;
  160. //Return error message
  161. if(count( $error)>0){
  162. if(isset($error[1])){
  163. $resultInfo['type'] = 1;
  164. $resultInfo['msg'] = $error[1];
  165. }else if(isset($error[2])){
  166. $resultInfo['type'] = 2;
  167. $resultInfo['msg'] = $error[2];
  168. }else if(isset($error[3] )){
  169. $resultInfo['type'] = 3;
  170. $resultInfo['msg'] = 'Header ['.implode(',',$error[3]).'] does not exist';
  171. }else if(isset($error[4])){
  172. $resultInfo['type'] = 4;
  173. $resultInfo['msg'] = $error[4];
  174. }else if(isset($error[6])){
  175. $resultInfo['type'] = 6;
  176. $resultInfo['msg'] = $error[6];
  177. }else if(isset($error[7])){
  178. $excelName = null;
  179. $objPHPWriteExcel = new PHPExcel();
  180. $objPHPWriteExcel->getProperties()->setCreator("yuer")
  181. ->setLastModifiedBy("yuer")->setTitle("")->setSubject("")
  182. ->setDescription("")->setKeywords("")->setCategory("");
  183. $prefix = substr($fileName,0,strrpos($fileName,'.'));
  184. $suffix = substr($fileName,strrpos($fileName,'.'));
  185. $excelName = date("Y_m_d_H_i_s").'_'.mt_rand(1,99).'_'.$prefix.'ErrorReport'.$suffix;
  186. $excelName = Base_Tool_Pinyin::getPinyin($excelName);
  187. $objPHPWriteExcel->setActiveSheetIndex(0);
  188. $activeSheet = $objPHPWriteExcel->getActiveSheet();
  189. $activeSheet->setTitle('错误报告');
  190. $activeSheet->setCellValueByColumnAndRow(0,1,self::PRODUCT_SAP_CODE);
  191. $activeSheet->setCellValueByColumnAndRow(1,1,'原excel行号');
  192. $activeSheet->setCellValueByColumnAndRow(2,1,'第几行编码存在重复');
  193. $activeSheet->setCellValueByColumnAndRow(3,1,self::PRODUCT_NAME);
  194. $activeSheet->setCellValueByColumnAndRow(4,1,self::PRODUCT_GROUP);
  195. $activeSheet->setCellValueByColumnAndRow(5,1,self::PRODUCT_BRAND);
  196. $activeSheet->setCellValueByColumnAndRow(6,1,self::PRODUCT_PROXY_FLAG);
  197. $activeSheet->setCellValueByColumnAndRow(7,1,self::PRODUCT_BINNING);
  198. $activeSheet->setCellValueByColumnAndRow(8,1,self::PRODUCT_SELL_PICK);
  199. $activeSheet->setCellValueByColumnAndRow(9,1,self::PRODUCT_ATTRIBUTE);
  200. $activeSheet->setCellValueByColumnAndRow(10,1,self::PRODUCT_SUPPLIER_CODE);
  201. $activeSheet->setCellValueByColumnAndRow(11,1,self::PRODUCT_SUPPLY_ADDRESS);
  202. $activeSheet->setCellValueByColumnAndRow(12,1,self::PRODUCT_BATCH);
  203. $activeSheet->setCellValueByColumnAndRow(13,1,'其他原因');
  204. $activeSheet->getColumnDimensionByColumn(0)->setWidth(15);
  205. $activeSheet->getColumnDimensionByColumn(1)->setWidth(20);
  206. $activeSheet->getColumnDimensionByColumn(2)->setWidth(20);
  207. $activeSheet->getColumnDimensionByColumn(3)->setWidth(20);
  208. $activeSheet->getColumnDimensionByColumn(4)->setWidth(20);
  209. $activeSheet->getColumnDimensionByColumn(5)->setWidth(20);
  210. $activeSheet->getColumnDimensionByColumn(6)->setWidth(20);
  211. $activeSheet->getColumnDimensionByColumn(7)->setWidth(20);
  212. $activeSheet->getColumnDimensionByColumn(8)->setWidth(20);
  213. $activeSheet->getColumnDimensionByColumn(9)->setWidth(20);
  214. $activeSheet->getColumnDimensionByColumn(10)->setWidth(20);
  215. $activeSheet->getColumnDimensionByColumn(11)->setWidth(20);
  216. $activeSheet->getColumnDimensionByColumn(12)->setWidth(20);
  217. $activeSheet->getColumnDimensionByColumn(13)->setWidth(20);
  218. $writeExcelIndex = 2;
  219. foreach ($error[7] as $pId=>$pInfo){
  220. if(isset($pInfo['hasId'])){
  221. $activeSheet->setCellValueByColumnAndRow(0,$writeExcelIndex,$pId.'-此供应商编码已经存在');
  222. } else {
  223. $activeSheet->setCellValueByColumnAndRow(0,$writeExcelIndex,$pId);
  224. }
  225. $activeSheet->setCellValueByColumnAndRow(1,$writeExcelIndex,$pInfo['excelRow']);
  226. if(isset($pInfo['duplicate'])){
  227. $activeSheet->setCellValueByColumnAndRow(2,$writeExcelIndex,$excelIdRow[$pId]);
  228. }
  229. if(isset($pInfo['emptyName'])){
  230. $activeSheet->setCellValueByColumnAndRow(3,$writeExcelIndex,'-为空');
  231. }
  232. if(isset($pInfo['emptyProductGroup'])){
  233. $activeSheet->setCellValueByColumnAndRow(4,$writeExcelIndex,'-为空');
  234. }
  235. if(isset($pInfo['emptyProductBrand'])){
  236. $activeSheet->setCellValueByColumnAndRow(5,$writeExcelIndex,'-为空');
  237. }
  238. if(isset($pInfo['emptyProductProxyFlag'])){
  239. $activeSheet->setCellValueByColumnAndRow(6,$writeExcelIndex,'-为空');
  240. }
  241. if(isset($pInfo['emptyProductBinning'])){
  242. $activeSheet->setCellValueByColumnAndRow(7,$writeExcelIndex,'-为空');
  243. }
  244. if(isset($pInfo['emptyProductSellPick'])){
  245. $activeSheet->setCellValueByColumnAndRow(8,$writeExcelIndex,'-为空');
  246. }
  247. if(isset($pInfo['emptyProductAttribute'])){
  248. $activeSheet->setCellValueByColumnAndRow(9,$writeExcelIndex,'-为空');
  249. }
  250. if(isset($pInfo['emptyVendorCode'])){
  251. $activeSheet->setCellValueByColumnAndRow(10,$writeExcelIndex,'-为空');
  252. }
  253. if(isset($pInfo['emptyZzwerkCode'])){
  254. $activeSheet->setCellValueByColumnAndRow(11,$writeExcelIndex,'-为空');
  255. }
  256. if(isset($pInfo['emptyZzlgortCode'])){
  257. $activeSheet->setCellValueByColumnAndRow(12,$writeExcelIndex,'-为空');
  258. }

  259. if(isset($pInfo['other'])){

  260. $activeSheet->setCellValueByColumnAndRow(13,$writeExcelIndex,$pInfp['other']);
  261. }
  262. $writeExcelIndex++;
  263. }
  264. $objWriter = PHPExcel_IOFactory::createWriter($objPHPWriteExcel, 'Excel5');
  265. $excelPath = FILE_PATH.DS.'feedback'.DS.$excelName;
  266. $objWriter->save($excelPath);
  267. $resultInfo['type'] = 7;
  268. $resultInfo['msg'] = $fileName."文件中存在错误";
  269. $resultInfo['errorReport'] = $excelName;
  270. // 日志操作,暂时空着
  271. }
  272. }else{
  273. //导入数据
  274. $logIds = '';
  275. $i = 0;
  276. foreach ($allProduct as $pId => $pInfo){
  277. $updateProductSql = 'insert into yr_product set ';
  278. if(isset($pInfo['pname']) && trim($pInfo['pname'])){
  279. $updateProductSql = $updateProductSql.'pname=''.str_replace(''','''',$pInfo['pname']).'',';
  280. }
  281. //如果SAP编码不足18位,则用0从左开始补全
  282. if(isset($pInfo['sap_code'])){
  283. if(strlen($pInfo['sap_code'])<18){
  284. $pInfo['sap_code'] = str_pad($pInfo['sap_code'], 18, "0", STR_PAD_LEFT);
  285. $updateProductSql = $updateProductSql.'sap_code=''.str_replace(''','''',$pInfo['sap_code']).'',';
  286. }
  287. }
  288. if(isset($pInfo['product_group'])){
  289. $updateProductSql = $updateProductSql.'product_group=''.$pInfo['product_group'].'',';
  290. }
  291. if(isset($pInfo['product_brand'])){
  292. $updateProductSql = $updateProductSql.'product_brand=''.$pInfo['product_brand'].'',';
  293. }
  294. if(isset($pInfo['product_proxy_flag'])){
  295. $updateProductSql = $updateProductSql.'product_proxy_flag=''.$pInfo['product_proxy_flag'].'',';
  296. }
  297. if(isset($pInfo['product_binning'])){
  298. $updateProductSql = $updateProductSql.'product_binning=''.$pInfo['product_binning'].'',';
  299. }
  300. if(isset($pInfo['product_sell_pick'])){
  301. $updateProductSql = $updateProductSql.'product_sell_pick=''.$pInfo['product_sell_pick'].'',';
  302. }
  303. if(isset($pInfo['product_attribute'])){
  304. $updateProductSql = $updateProductSql.'product_attribute=''.$pInfo['product_attribute'].'',';
  305. }
  306. if(isset($pInfo['vendor_code'])){
  307. $updateProductSql = $updateProductSql.'vendor_code=''.$pInfo['vendor_code'].'',';
  308. }
  309. if(isset($pInfo['zzwerk_code'])){
  310. $updateProductSql = $updateProductSql.'zzwerk_code=''.$pInfo['zzwerk_code'].'',';
  311. }
  312. if(isset($pInfo['zzlgort_code'])){
  313. $updateProductSql = $updateProductSql.'zzlgort_code=''.$pInfo['zzlgort_code'].''';
  314. }
  315. //Final SQL statement
  316. $result = $this->excuteMultiInsertSql($updateProductSql);
  317. }
  318. $resultInfo['type'] = 8;
  319. $resultInfo['msg'] = "Importing basic product information successfully";

  320. /*

  321. * // Log operation.
  322. * $content = 'Batch new product import operation successful: imported supply product codes are ->';
  323. * $logData['content'] = $content. $logIds;
  324. */
  325. }
  326. return $resultInfo;
  327. }

Copy code


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn