读取工作表中的所有单元格(包括 Excel 工作表中的空白单元格)的 Java 代码,并将相同的数据插入 postgresql 数据库而不对其进行编辑。
我已经尝试过使用 apache-poi、missingcellpolicy、replacefunction 等。但是,它会抛出空指针异常。
当我运行代码来显示 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 的“依赖项”下(如果使用 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、列标题或枚举来获取其值,尽管这些需要定义。然后通过相应的存储库将这些值保存到相关的数据库实体中。
关于java - 如何使用java将excel表中的数据插入数据库(包括空格而不编辑它们),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58558144/