从这里下载 apache poi jar
浏览这些示例,这些示例演示了如何从 java 程序中读取/写入 xls 数据示例帮助代码:
public static void main(String[] args) throws IOException {
Workbook wb = new HSSFWorkbook();
Sheet sheet = wb.createSheet("sheet");
Row row = sheet.createRow((short) 0);
row.createCell(0).setCellValue(1.2);
row.createCell(1).setCellValue(wb.getCreationHelper().createRichTextString("This is a string"));
row.createCell(2).setCellValue(true);
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
}
这可能会帮助您入门。整个流程是:
- 创建工作簿 => 主 xls 文件
- 然后创建一张表
- 然后创建一行。
- 为每一行创建任意数量的单元格,并用不同的值填充单元格
- 像文件一样编写工作簿。
可以有多种类型的单元格,请参阅此以获取更多信息。要了解如何读取 excel 文件:
InputStream myxls = new FileInputStream("workbook.xls");
wb = new HSSFWorkbook(myxls);
sheet = wb.getSheetAt(0); // first sheet
row = sheet.getRow(0); // third row
HSSFCell cell = (HSSFCell) row.getCell((short)1); // fourth cell
if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
System.out.println("The Cell was a String with value \" " + cell.getStringCellValue()+" \" ");
} else if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
System.out.println("The cell was a number " + cell.getNumericCellValue());
} else {
System.out.println("The cell was nothing we're interested in");
}
有关更多信息,请参阅此