我已成功使用Apache POI API使用Java创建了.xlsx格式的工作簿/ Excel。我的代码如下所示,创建了一个名为" RiponAlWasim.xlsx"的文件。在D盘:
Workbook wb = new XSSFWorkbook();
FileOutputStream fileOut = new FileOutputStream("D:\\RiponAlWasim.xlsx");
wb.write(fileOut);
fileOut.close();
wb.close();
当我试图打开" RiponAlWasim.xlsx"它显示文件已损坏。什么是错的?
答案 0 :(得分:8)
需要在工作簿中添加至少一个工作表。因此,在创建工作表后,以下代码运行良好:
Workbook wb = new XSSFWorkbook();
Sheet sheet1 = wb.createSheet("Ripon");
FileOutputStream fileOut = new FileOutputStream("D:\\RiponAlWasim.xlsx");
wb.write(fileOut);
fileOut.close();
wb.close();
答案 1 :(得分:0)
excel 损坏的原因:由于循环语句中的错误导致 excel 关闭不当
在循环内使用 try-catch 块,以便在 catch 块中
循环后
答案 2 :(得分:-2)
我遇到了同样的问题,但我找到了解决方案。下面是我完整的代码,用于读取和编写excel而不会损坏文件。
package utility;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelPOI {
private static File file;
public ExcelPOI(String path){
file = new File(path);
if (!file.exists()) {
System.out.println("File does not exist.");
file=null;
}
}
public String getText(String sheetName, int row, int col) throws Exception
{
InputStream ExcelFileToRead = new FileInputStream(file);
String Value;
XSSFWorkbook wb = new XSSFWorkbook(ExcelFileToRead);
XSSFSheet sheet=wb.getSheet(sheetName);
if(row>=0 && col>=0){
try{
Value = sheet.getRow(row).getCell(col).getStringCellValue();
ExcelFileToRead.close();
wb.close();
}catch(Exception e){
System.out.println("Row or Cell not created.");
ExcelFileToRead.close();
wb.close();
return null;
}
return Value;
}else{
System.out.println("Plz Enter a positive Row and Column");
}
ExcelFileToRead.close();
wb.close();
return null;
}
public void setText(String sheetName, int rowNum, int col, String value) throws IOException, InvalidFormatException {
FileInputStream fio = new FileInputStream(file);
XSSFWorkbook wb = new XSSFWorkbook(fio);
XSSFSheet sheet = wb.getSheet(sheetName);
XSSFRow row;
if(rowNum>=0 && col>=0){
try{
row = sheet.getRow(rowNum);
XSSFCell cell = row.createCell(col);
cell.setCellValue(value);
}catch(Exception e){
System.out.println("Row Creation Required..");
row = sheet.createRow(rowNum);
XSSFCell cell = row.createCell(col);
cell.setCellValue(value);
}
}else{
System.out.println("Plz Enter a positive Row and Column");
}
fio.close();
FileOutputStream fileOut = new FileOutputStream(file);
//write this workbook to an Outputstream.
wb.write(fileOut);
wb.close();
fileOut.flush();
fileOut.close();
}
}