java将excel转成sql建表语句
时间: 2023-12-03 09:01:45 浏览: 290
Java sql语句设计建表
以下是将 Excel 转换成 SQL 建表语句的 Java 代码示例:
```java
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
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;
public class ExcelToSqlConverter {
public static void main(String[] args) throws IOException {
// 读取 Excel 文件
FileInputStream inputStream = new FileInputStream(new File("input.xlsx"));
Workbook workbook = new XSSFWorkbook(inputStream);
Sheet sheet = workbook.getSheetAt(0);
// 获取表名
String tableName = sheet.getSheetName();
// 遍历 Excel 表格数据
Iterator<Row> iterator = sheet.iterator();
while (iterator.hasNext()) {
Row currentRow = iterator.next();
StringBuilder sqlBuilder = new StringBuilder();
if (currentRow.getRowNum() == 0) { // 第一行为表头,生成表结构
sqlBuilder.append("CREATE TABLE ").append(tableName).append(" (");
Iterator<Cell> cellIterator = currentRow.iterator();
while (cellIterator.hasNext()) {
Cell currentCell = cellIterator.next();
sqlBuilder.append(currentCell.getStringCellValue()).append(" VARCHAR(255), ");
}
sqlBuilder.delete(sqlBuilder.length() - 2, sqlBuilder.length()); // 去掉最后一个逗号
sqlBuilder.append(");");
} else { // 生成数据插入语句
sqlBuilder.append("INSERT INTO ").append(tableName).append(" VALUES (");
Iterator<Cell> cellIterator = currentRow.iterator();
while (cellIterator.hasNext()) {
Cell currentCell = cellIterator.next();
if (currentCell.getCellType() == Cell.CELL_TYPE_STRING) {
sqlBuilder.append("'").append(currentCell.getStringCellValue()).append("', ");
} else if (currentCell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
sqlBuilder.append(currentCell.getNumericCellValue()).append(", ");
}
}
sqlBuilder.delete(sqlBuilder.length() - 2, sqlBuilder.length()); // 去掉最后一个逗号
sqlBuilder.append(");");
}
System.out.println(sqlBuilder.toString());
}
workbook.close();
inputStream.close();
}
}
```
这段代码可以将 Excel 文件中的数据转换成 SQL 建表语句和数据插入语句,你只需要修改 "input.xlsx" 为你要转换的 Excel 文件名即可。
阅读全文