PHP reads Excel file content and writes it to database

Original link: https://5ime.cn/excel2sql.html

I recently encountered a need to import an Excel类型question bank into the database (the specific format is shown in the figure below), and Baidu found a suitable library PhpSpreadsheet

PhpSpreadsheet is a library written in pure PHP that provides a set of classes that allow you to read and write various spreadsheet file formats, such as Excel and LibreOffice Calc.

image-20221114171259581

database

First design the database, id ,题目,答案, and类型must be four.

 1
2
3
4
5
6
7
8
9
10
 SET FOREIGN_KEY_CHECKS = 0 ;
DROP TABLE IF EXISTS `questions`;
CREATE TABLE `questions` (
`id` int ( 11 ) NOT NULL AUTO_INCREMENT,
`title` varchar ( 255 ) NOT NULL ,
`options` text NOT NULL ,
`answer` varchar ( 255 ) NOT NULL ,
`type` varchar ( 255 ) NOT NULL ,
PRIMARY KEY (`id`)
) ENGINE = MyISAM AUTO_INCREMENT = 1 DEFAULT CHARSET = utf8;

Install

 1
 composer require phpoffice/phpspreadsheet

the code

Notes are written in the key places, here you can modify it according to the actual situation

 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
twenty one
twenty two
twenty three
twenty four
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
 <?php
require 'vendor/autoload.php' ;

// 连接数据库
$servername = "localhost" ;
$username = "username" ;
$password = "password" ;
$dbname = "question" ;

$conn = new mysqli ( $servername , $username , $password , $dbname );

if ( $conn ->connect_error) {
die ( "Connection failed: " . $conn ->connect_error);
}

// 读取excel文件
$reader = \PhpOffice\PhpSpreadsheet\ IOFactory :: createReader ( 'Xlsx' );
$reader -> setReadDataOnly ( TRUE );
$spreadsheet = $reader -> load ( "question.xlsx" );

$array = [];
// 循环遍历所有Sheet
// [0]=题目[1]=A [2]=B [3]=C [4]=D ... 最后一项为正确答案
foreach ( $spreadsheet -> getAllSheets () as $sheet ) {
$sheetName = $sheet -> getTitle ();
$sheetData = $sheet -> toArray ();
$sheetData = array_slice ( $sheetData , 1 ); // 去掉第一行标题
$sheetData = array_filter ( $sheetData , function ( $item ) {
return ! empty ( $item [ 0 ]);
}); // 去掉空行
foreach ( $sheetData as $item ) {
// 最后一个为选项
$options = array_slice ( $item , 1 , - 1 );
$options = array_filter ( $options , function ( $item ) {
return ! empty ( $item );
}); // 去掉空选项
$array [] = [
'question' => $item [ 0 ],
'options' => $options ,
// 每个字符都进行分割,主要为了分割出多选
'answer' => str_split ( $item [ count ( $item ) - 1 ]),
'type' => $sheetName
];
}
}

// 插入数据库
foreach ( $array as $item ) {
$question = $item [ 'question' ];
$options = addslashes ( json_encode ( $item [ 'options' ]));
$answer = addslashes ( json_encode ( $item [ 'answer' ]));
$type = $item [ 'type' ];
$sql = "INSERT INTO `questions` (`title`, `options`, `answer`, `type`) VALUES (' $question ', ' $options ', ' $answer ', ' $type ')" ;
$conn -> query ( $sql );
}

// 查询数据库
$jsonData = [];
$sql = "SELECT * FROM `questions`" ;
$result = $conn -> query ( $sql );
if ( $result ->num_rows > 0 ) {
while ( $row = $result -> fetch_assoc ()) {
$row [ 'options' ] = json_decode ( $row [ 'options' ], true );
$row [ 'answer' ] = json_decode ( $row [ 'answer' ], true );
$jsonData [] = $row ;
}
}
echo $Json = json_encode ( $jsonData ,JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE);

example

The data inserted into the数据库is as follows

id title options answer type
1 In what year was the first use of elliptic curves in cryptography, the algorithm for establishing public-key cryptography? [“1982\u5e74”, “1985\u5e74”, “1990\u5e74”, “1992\u5e74”] [“B”] radio
2 In the long run, the application of blockchain can be divided into ( ) stages. [“\u53ef\u4fe1\u534f\u540c\u5e73\u53f0”, “\u4e1a\u52a1\u96c6\u4e2d\u5904\u7406”, “\u6807\u51c6\u4ef7\u503c\u4f20\u8f93\u9636\u6bb5”, “\u5206\u5e03\u5f0f\u5546\u4e1a\u57fa\u7840\u8bbe\u65bd”] [“A”,”C”,”D”] multiple choice
3 Cloud computing is an important infrastructure for big data storage and analysis. [“\u5bf9”, “\u9519”] [“A”] judge

The json data returned by the query is as follows

 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
 [ {
"id" : "1" ,
"question" : "首次将椭圆曲线用于密码学,建立公开密钥加密的演算法是在那一年?" ,
"options" : [ "1982年" , "1985年" , "1990年" , "1992年" ] ,
"answer" : [ "B" ] ,
"type" : "单选"
} , {
"id" : "2" ,
"question" : "从长远来看,区块链的应用可以分为( )阶段。" ,
"options" : [ "可信协同平台" , "业务集中处理" , "标准价值传输阶段" , "分布式商业基础设施" ] ,
"answer" : [ "A" , "C" , "D" ] ,
"type" : "多选"
} , {
"id" : "3" ,
"question" : "云计算是大数据存储和分析的重要基础设施。" ,
"options" : [ "对" , "错" ] ,
"answer" : [ "A" ] ,
"type" : "判断"
} ]

This article is transferred from: https://5ime.cn/excel2sql.html
This site is for inclusion only, and the copyright belongs to the original author.