search
HomeBackend DevelopmentPHP TutorialSample code for phpexcel to import excel data

  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 $cValue = trim($objWorksheet->getCellByColumnAndRow($i,1)->getValue());
  35. switch ($cValue) {
  36. case self ::PRODUCT_SAP_CODE : $colums[$i] = "sap_code"; break;
  37. case self::PRODUCT_NAME : $colums[$i] = "pname"; break;
  38. case self::PRODUCT_GROUP : $colums[$i] = "product_group"; break;
  39. case self::PRODUCT_BRAND : $colums[$i] = 'product_brand'; break;
  40. case self::PRODUCT_PROXY_FLAG : $colums[$i] = "product_proxy_flag"; break;
  41. case self ::PRODUCT_BINNING : $colums[$i] = "product_binning"; break;
  42. case self::PRODUCT_SELL_PICK : $colums[$i] = "product_sell_pick"; break;
  43. case self::PRODUCT_ATTRIBUTE : $colums[$i] = "product_attribute"; break;
  44. case self::PRODUCT_SUPPLIER_CODE : $colums[$i] = "vendor_code"; break;
  45. case self::PRODUCT_SUPPLY_ADDRESS : $colums[$i] = "zzwerk_code"; break;
  46. case self ::PRODUCT_BATCH : $colums[$i] = "zzlgort_code"; break;
  47. default : $error[3][] = $cValue; break;
  48. }
  49. }
  50. //Detect whether basic information in Excel exists
  51. $ dataCount = $highestRow - 1;
  52. if(count($colums) == 0) {
  53. $error[5] = "No header";
  54. }
  55. else if(!in_array('sap_code',$colums)) {
  56. $error[2] = "The product SAP code in the header does not exist";
  57. }
  58. else if($dataCount $error[6] = "There is no data in the Excel file";
  59. }
  60. else if(count($error)==0){
  61. for ($i=2;$i $colkey = array_search('sap_code');
  62. $shopLinkedIdValue = trim( $objWorksheet->getCellByColumnAndRow($colkey,$i)->getValue());
  63. if(!$shopLinkedIdValue) {
  64. continue;
  65. }
  66. if(in_array($shopLinkedIdValue,$execlAllShopLinkedId)){
  67. $error [7][$shopLinkedIdValue]['duplicate'] = true;
  68. $error[7][$shopLinkedIdValue]['excelRow'][] = $i;
  69. $execlAllShopLinkedId[$i] = $shopLinkedIdValue;
  70. $error [7][$shopLinkedIdValue]['noId'] = true;
  71. }else {
  72. $excelIdRow[$shopLinkedIdValue] = $i;
  73. $execlAllShopLinkedId[$i] = $shopLinkedIdValue;
  74. }
  75. }
  76. $dealMultiple = ceil($dataCount / 1000);
  77. $allProduct = array();
  78. for($i=0;$i $offset = $i*1000+2;
  79. $max = ($i+1)*1000+1;
  80. $max = ($max > $dataCount) ? $highestRow : $max;
  81. $allShopLinkedId = array();
  82. for($j=$offset; $j if($execlAllShopLinkedId[$j]){
  83. $allShopLinkedId[] = $execlAllShopLinkedId[$j];
  84. }
  85. }
  86. // Query in the library based on SAP product code The number of records.
  87. $dbShopProducts = $this->getShopLinkedByIds($allShopLinkedId);
  88. for($j=$offset;$j $ product = array();

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

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

  313. * // Log operation.
  314. * $content = 'Batch new product import operation successful: imported supply product codes are ->';
  315. * $logData['content'] = $content. $logIds;
  316. */
  317. }
  318. return $resultInfo;
  319. }
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
PHP: An Introduction to the Server-Side Scripting LanguagePHP: An Introduction to the Server-Side Scripting LanguageApr 16, 2025 am 12:18 AM

PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.

PHP and the Web: Exploring its Long-Term ImpactPHP and the Web: Exploring its Long-Term ImpactApr 16, 2025 am 12:17 AM

PHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.

Why Use PHP? Advantages and Benefits ExplainedWhy Use PHP? Advantages and Benefits ExplainedApr 16, 2025 am 12:16 AM

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

Debunking the Myths: Is PHP Really a Dead Language?Debunking the Myths: Is PHP Really a Dead Language?Apr 16, 2025 am 12:15 AM

PHP is not dead. 1) The PHP community actively solves performance and security issues, and PHP7.x improves performance. 2) PHP is suitable for modern web development and is widely used in large websites. 3) PHP is easy to learn and the server performs well, but the type system is not as strict as static languages. 4) PHP is still important in the fields of content management and e-commerce, and the ecosystem continues to evolve. 5) Optimize performance through OPcache and APC, and use OOP and design patterns to improve code quality.

The PHP vs. Python Debate: Which is Better?The PHP vs. Python Debate: Which is Better?Apr 16, 2025 am 12:03 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on the project requirements. 1) PHP is suitable for web development, easy to learn, rich community resources, but the syntax is not modern enough, and performance and security need to be paid attention to. 2) Python is suitable for data science and machine learning, with concise syntax and easy to learn, but there are bottlenecks in execution speed and memory management.

PHP's Purpose: Building Dynamic WebsitesPHP's Purpose: Building Dynamic WebsitesApr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP: Handling Databases and Server-Side LogicPHP: Handling Databases and Server-Side LogicApr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

How do you prevent SQL Injection in PHP? (Prepared statements, PDO)How do you prevent SQL Injection in PHP? (Prepared statements, PDO)Apr 15, 2025 am 12:15 AM

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.