我正在尝试将数据附加到现有的excel文件中,但没有写入任何内容。我做错了什么?
public static void writeSheet(String data) {
HSSFWorkbook workbook;
try {
String outFileName = "filebook.xls";
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
File outFile = new File(path, outFileName);
workbook = (HSSFWorkbook) WorkbookFactory.create(outFile);
Row row = workbook.getSheetAt(0).createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("text");
OutputStream outputStream = new FileOutputStream(outFile,true);
workbook.write(outputStream);
outputStream.close();
workbook.close();
} catch (Exception e) {
e.printStackTrace();
}
}
答案 0 :(得分:3)
相反
File outFile = new File(path, outFileName);
workbook = (HSSFWorkbook) WorkbookFactory.create(outFile);
尝试
FileInputStream outFile = new FileInputStream(new File(path));
workbook = new HSSFWorkbook(outFile);
所以你的代码
public static void writeSheet(String data) {
HSSFWorkbook workbook;
try {
String outFileName = "filebook.xls";
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
FileInputStream file = new FileInputStream(new File(path, outFileName))
workbook = new HSSFWorkbook(file);
Row row = workbook.getSheetAt(0).createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("text");
file.close();
FileOutputStream outFile =new FileOutputStream(new File(path, outFileName));
workbook.write(outFile);
outFile.close();
} catch (Exception e) {
e.printStackTrace();
}
}
答案 1 :(得分:0)
如果您要使用java
创建Excell文件File file = new File(filename);
WorkbookSettings wbSettings = new WorkbookSettings();
wbSettings.setLocale(new Locale("en", "EN"));
WritableWorkbook workbook = Workbook.createWorkbook(file,
wbSettings);
workbook.createSheet("My_excell_file", 0);
WritableSheet excelSheet = workbook.getSheet(0);
WritableFont ledgerFont = new WritableFont(
WritableFont.createFont("Arial"),
WritableFont.DEFAULT_POINT_SIZE, WritableFont.BOLD, false,
UnderlineStyle.NO_UNDERLINE, Colour.GRAY_80);
Label labelhead1;
Label labelhead2;
Label labelhead3;
private WritableCellFormat headFormat, langFormat;
labelhead1 = new Label(0, 1, "KEY", this.headFormat);
labelhead2 = new Label(1, 1, "VALUE", this.headFormat);
labelhead3 = new Label(2, 1, "PROPERTY", this.headFormat);
excelSheet.addCell(labelhead1);
excelSheet.addCell(labelhead2);
excelSheet.addCell(labelhead3);
workbook.write();
workbook.close();
// For Update
HSSFRow row;
row = sheet.getRow(0);
cell = row.getCell(0);
cell.setCellValue("Updated Values");