使用java从“大型Excel 2003”文件中检索选择性表数据
使用java从“大型Excel 2003”文件中检索选择性表数据
我想从Java中读取和写入一个包含3列和N行的Excel文件,在每个单元格中打印一个字符串。有没有人能给我一段简单的代码片段?我需要使用任何外部库还是Java已经内置支持了它? 我想要做以下事情:
for(i=0; i <rows; i++) //read [i,col1] ,[i,col2], [i,col3] for(i=0; i<rows; i++) //write [i,col1], [i,col2], [i,col3]
admin 更改状态以发布 2023年5月21日
Apache POI可以帮助您完成。具体来说,是通过HSSF模块实现的。 快速指南是最有用的。以下是实现您所需的方法——创建一个工作表并将其写出。
Workbook wb = new HSSFWorkbook(); //Workbook wb = new XSSFWorkbook(); CreationHelper createHelper = wb.getCreationHelper(); Sheet sheet = wb.createSheet("new sheet"); // Create a row and put some cells in it. Rows are 0 based. Row row = sheet.createRow((short)0); // Create a cell and put a value in it. Cell cell = row.createCell(0); cell.setCellValue(1); // Or do it on one line. row.createCell(1).setCellValue(1.2); row.createCell(2).setCellValue( createHelper.createRichTextString("This is a string")); row.createCell(3).setCellValue(true); // Write the output to a file FileOutputStream fileOut = new FileOutputStream("workbook.xls"); wb.write(fileOut); fileOut.close();
试试Apache POI HSSF。这里有一个读取Excel文件的例子:
try { POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(file)); HSSFWorkbook wb = new HSSFWorkbook(fs); HSSFSheet sheet = wb.getSheetAt(0); HSSFRow row; HSSFCell cell; int rows; // No of rows rows = sheet.getPhysicalNumberOfRows(); int cols = 0; // No of columns int tmp = 0; // This trick ensures that we get the data properly even if it doesn't start from first few rows for(int i = 0; i < 10 || i < rows; i++) { row = sheet.getRow(i); if(row != null) { tmp = sheet.getRow(i).getPhysicalNumberOfCells(); if(tmp > cols) cols = tmp; } } for(int r = 0; r < rows; r++) { row = sheet.getRow(r); if(row != null) { for(int c = 0; c < cols; c++) { cell = row.getCell((short)c); if(cell != null) { // Your code here } } } } } catch(Exception ioe) { ioe.printStackTrace(); }
在文档页面上还有写入Excel文件的示例。