编写工具类
bash
package com.zxl;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class XlsxTool {
// TODO: 2025/11/24 file是地址 ,isHeader 是否去掉表头
public static String xlsx(String files, Boolean isHeader) throws IOException {
// TODO: 2025/11/24 读取Excel文件:使用FileInputStream打开Excel文件,并创建HSSFWorkbook或XSSFWorkbook对象。
FileInputStream file = new FileInputStream(new File(files));
Workbook workbook = new XSSFWorkbook(file);
// TODO: 2025/11/24 遍历工作表和单元格:通过工作簿对象获取工作表,然后遍历行和单元格来读取数据。
Sheet sheet = workbook.getSheetAt(0);
int num;
if (isHeader) {
num = sheet.getRow(0).getRowNum() + 1;
} else {
num = sheet.getRow(0).getRowNum();
}
String values = "insert into table values";
for (int i = num; i <= sheet.getLastRowNum(); i++) {
Row sheetRow = sheet.getRow(i);
// TODO: 2025/11/24 每行最后一个单元格
int lastCellNum = sheetRow.getLastCellNum() - 1;
// TODO: 2025/11/24 创建SQL变量进行拼接
String sql = "(";
for (Cell cell : sheetRow) {
// TODO: 2025/11/24 每个单元格的下标
int index = cell.getColumnIndex();
// TODO: 2025/11/24 对每个单元格的数值类型进行判断取值
switch (cell.getCellType()) {
case STRING:
if (index < lastCellNum) {
sql += '"' + cell.getStringCellValue() + '"' + ',';
} else {
sql += '"' + cell.getStringCellValue() + '"';
}
break;
case NUMERIC:
if (index < lastCellNum) {
sql += '"' + String.valueOf(cell.getNumericCellValue()) + '"' + ',';
} else {
sql += '"' + String.valueOf(cell.getNumericCellValue()) + '"';
}
break;
case BOOLEAN:
if (index < lastCellNum) {
sql += '"' + "null" + '"' + ',';
} else {
sql += '"' + "null" + '"';
}
break;
default:
System.out.print(" " + "\t");
}
}
// TODO: 2025/11/24 判断是否是最后一行,如果是拼接分号
if (i < sheet.getLastRowNum()) {
sql += "),";
} else {
sql += ");";
}
values += sql;
}
System.out.println(values);
// TODO: 2025/11/24 关闭资源:读取完数据后,关闭FileInputStream和工作簿对象以释放资源。
workbook.close();
file.close();
return null;
}
}
测试运行

bash
package com.zxl;
import java.io.IOException;
public class DemoTest {
public static void main(String[] args) throws IOException {
String file="D:\\XueLiang\\SparkWorks\\SparkSqlCoreTest\\src\\main\\resources\\zhang.xlsx";
Boolean isHeader=false;
String xlsx = XlsxTool.xlsx(file, isHeader);
}
}
bash
insert into table values("姓名","年龄","地址","手机号","学校"),("张三","23.0","阿斯兰大富科技阿是","qreqwerqwe","阿斯顿发"),("历史","gsd","阿斯顿发顺丰","dsafasdfasd","沃尔沃"),("慰问费","234.0","讽德诵功合适的","对方过后","343.0");
