-5

我正在尝试将数据写入 excel 表。但是当我使用 workbook.write(fileout) 时它失败了。我通过互联网但每个人都说问题出在构建路径中。我使用了 ooxml_schemas-1.1.jar每个人都建议但没有用..任何人都可以帮我解决这个问题吗?提前致谢

4

2 回答 2

2

您可以使用 Apache POI来完成。

Apache POI 是一个强大的 Java 库,可以处理不同的 Microsoft Office 文件格式,例如 Excel、Power point、Visio、MS Word 等。 POI 这个名字最初是Poor Obfuscation Implementation 的首字母缩写,幽默地指的是文件格式似乎故意混淆,但效果不佳,因为它们被成功地逆向工程。

于 2013-07-18T12:26:28.843 回答
2

创建新的excel文件

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
//..
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Sample sheet");
//Create a new row in current sheet
Row row = sheet.createRow(0);
//Create a new cell in current row
Cell cell = row.createCell(0);
//Set value to new value
cell.setCellValue("Blahblah");

然后将数据写入该excel文件

HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Sample sheet");

Map<String, Object[]> data = new HashMap<String, Object[]>();
data.put("1", new Object[] {"Emp No.", "Name", "Salary"});
data.put("2", new Object[] {1d, "John", 1500000d});
data.put("3", new Object[] {2d, "Sam", 800000d});
data.put("4", new Object[] {3d, "Dean", 700000d});

Set<String> keyset = data.keySet();
int rownum = 0;
for (String key : keyset) {
    Row row = sheet.createRow(rownum++);
    Object [] objArr = data.get(key);
    int cellnum = 0;
    for (Object obj : objArr) {
        Cell cell = row.createCell(cellnum++);
        if(obj instanceof Date) 
            cell.setCellValue((Date)obj);
        else if(obj instanceof Boolean)
            cell.setCellValue((Boolean)obj);
        else if(obj instanceof String)
            cell.setCellValue((String)obj);
        else if(obj instanceof Double)
            cell.setCellValue((Double)obj);
    }
}

try {
    FileOutputStream out = 
            new FileOutputStream(new File("C:\\new.xls"));
    workbook.write(out);
    out.close();
    System.out.println("Excel written successfully..");

} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}
于 2013-07-18T12:26:44.343 回答