public static void createworkbook() throws IOException, InvalidFormatException{
File file = new File("C:\\Workspace\\Selenium_2.53\\src\\InputFiles\\webuyPurchase.xlsx");
file.createNewFile();
fileOut = new FileOutputStream(file);
XSSFWorkbook workbook = new XSSFWorkbook();
workbook.write(fileOut);
XSSFSheet spreadsheet = workbook.createSheet("Products");
String sheetname = workbook.getSheetAt(0).getSheetName();
System.out.println(sheetname);
fileOut.close();
// workbook.createSheet("Products");
System.out.println("workbook is created");
}
执行上述代码时,File已成功创建。但是在打开文件时发现文件已损坏。
答案 0 :(得分:3)
当您更正了陈述的顺序时,它应该看起来像这样......
因此,没有必要事先通过file.createNewFile()
创建文件
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class CreateWorkbook {
public static void main(String args[]) throws IOException {
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet spreadsheet = workbook.createSheet("Products");
spreadsheet.createRow(0).createCell(0).setCellValue("this is a test");
FileOutputStream fos = new FileOutputStream("bla.xlsx");
workbook.write(fos);
fos.close();
workbook.close();
}
}