如何使用java将excel表中的数据插入数据库(包括空格而不进行编辑)



Java代码,用于读取工作表中的所有单元格,包括excel工作表的空白单元格,并在不编辑的情况下将相同的数据插入postgresql数据库。

我已经尝试过使用apache poi、missingcellpolicy、replacefunction等。但是,它抛出了一个nullpointerexception。

当我运行代码在excel中显示单元格的单元格类型时,它不会显示空格的任何类型,而是完全跳过单元格。

这是代码:

package poiexcel;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.Format;
import java.text.SimpleDateFormat;
//import java.util.ArrayList;
import java.util.Date;
//import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
@SuppressWarnings("unused")
public class ReadExcel {
public static final String SAMPLE_XLSX_FILE_PATH = "C:\Raj's Documents\Documents\studentdata.xlsx";
public static void main(String[] args) throws IOException, InvalidFormatException {
try {
FileInputStream file = new FileInputStream(new File(SAMPLE_XLSX_FILE_PATH));// Read the spreadsheet that
                  // needs to be uploaded
XSSFWorkbook myExcelBook = new XSSFWorkbook(file);
DataFormatter dataFormatter = new DataFormatter();
for (Sheet myExcelsheet : myExcelBook) {
//              ArrayList<SheetDetails> details = new ArrayList<SheetDetails>();
//              for (Row row : myExcelsheet) {
for (int i = 0; i < myExcelsheet.getPhysicalNumberOfRows(); i++) {
Row row = myExcelsheet.getRow(i);
for (int j = 0; j < row.getPhysicalNumberOfCells(); j++) {
Cell cell = row.getCell(j);
CellType ct = cell.getCellType();
System.out.println(ct);
}
System.out.println();
}
}
myExcelBook.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}

这是输出:

数字字符串java.lang.NullPointerException在poiexcel。ReadExcel.main(ReadExcel.java:52(

在build.gradle中的"dependencies"下(如果使用gradle,则为Maven找到匹配的依赖项(文件粘贴我们想要的依赖项:

编译组:"org.apache.commons",名称:"commons-csv",版本:"1.5">

创建以下导入:

import org.apache.commons.csv.*;

分析excel csv文件就像一样简单

public Iterable<CSVRecord> parse(String csvPath) throws IOException {
Reader in = new FileReader(csvPath);
return CSVFormat.EXCEL.withFirstRecordAsHeader().parse(in);
}

如果csv文件是纯文本csv文件,则EXCEL可以更改为DEFAULT。

然后,我们可以使用可迭代列表通过id、列标题或枚举获取其值,尽管这些值需要定义。然后通过相应的存储库将这些值持久化到相关的数据库实体中。

相关内容

最新更新