使用Apache POI 3.17在java中使用文件写入时文件已损坏

时间:2018-06-04 19:04:06

标签: java apache-poi

InputStream is = getAssets().open("images/names.txt");
BufferedReader br = new BufferedReader(is);

它第一次工作,文本“ibrahim01”出现在单元格上然而当我第二次运行它时我得到了这个错误: -

public class ClassA1 {
   private static Workbook wb;
   private static FileOutputStream fos;
   private static FileInputStream fis;
   private static org.apache.poi.ss.usermodel.Sheet sh;
   private static Row row;
   private static Cell cell;

public static void main(String[] args) throws Exception {

    fis = new FileInputStream("./javabook.xlsx");
    wb = WorkbookFactory.create(fis);
    sh = wb.getSheet("Sheet1");
    row =sh.getRow(1);
    cell = row.createCell(0);
    cell.setCellValue("ibrahim1");

    fos = new FileOutputStream("./javabook.xlsx");
    wb.write(fos);
    fos.close();
    System.out.println("Done");


   }
}

打开文件时的错误图片(javabook.xlsx) enter image description here

1 个答案:

答案 0 :(得分:1)

试试这个

import java.io.FileOutputStream;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ClassA1 {
    private static XSSFWorkbook wb;
    private static FileOutputStream fos;
    private static XSSFSheet sh;
    private static Row row;
    private static Cell cell;

    public static void main(String[] args) throws Exception {

        wb = new XSSFWorkbook();
        sh = wb.createSheet("Sheet1");
        row = sh.createRow(0);
        cell = row.createCell(0);
        cell.setCellValue("ibrahim1");

        fos = new FileOutputStream("./javabook.xlsx");
        wb.write(fos);
        fos.close();
        System.out.println("Done");

    }
}