Jakarta的POI项目提供了一组操纵Windows文档的Java API,如下几个类提供了操作Excel文件的方便的途径:HSSFWorkbook、HSSFSheet、HSSFRow、HSSFCell,分别代表了Excel电子表格中的Book、Sheet、行和单元格。 你可以在下面地址下载到最新的POI工具包: http://jakarta.apache.org/poi/index.html 下面的代码创建一个Excel文件test.xls,并在第一行的第一格中写入一条消息: import org.apache.poi.hssf.usermodel.*; import java.io.FileOutputStream; // code run against the jakarta-poi-1.5.0-FINAL-20020506.jar. public class PoiTest { static public void main(String[] args) throws Exception { FileOutputStream fos = new FileOutputStream("d:/test.xls"); HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet s = wb.createSheet(); wb.setSheetName(0, "first sheet"); HSSFRow row = s.createRow(0); HSSFCell cell = row.createCell(0); cell.setCellValue("Hello! This message is generated from POI."); wb.write(fos); fos.close(); } } 读取Excel文件时,首先生存一个POIFSFileSystem对象,由POIFSFileSystem对象构造一个HSSFWorkbook,该HSSFWorkbook对象就代表了Excel文档。下面代码读取上面生成的Excel文件写入的消息字串: POIFSFileSystem fs = null; HSSFWorkbook wb = null; try { fs = new POIFSFileSystem(new FileInputStream("d:/test.xls")); wb = new HSSFWorkbook(fs); } catch (IOException e) { e.printStackTrace(); } HSSFSheet sheet = wb.getSheetAt(0); HSSFRow row = sheet.getRow(0); HSSFCell cell = row.getCell((short) 0); String msg = cell.getStringCellValue(); 另外一个例子: import org.apache.poi.hssf.usermodel.*; import java.io.FileOutputStream; import java.io.IOException; public class CreateCells { public static void main(String[] args) throws IOException { HSSFWorkbook wb = new HSSFWorkbook(); //建立新HSSFWorkbook对象 HSSFSheet sheet = wb.createSheet("new sheet"); //建立新的sheet对象 // Create a row and put some cells in it. Rows are 0 based. HSSFRow row = sheet.createRow((short)0); //建立新行 // Create a cell and put a value in it. HSSFCell cell = row.createCell((short)0); //建立新cell cell.setCellvalue(1);//设置cell的整数类型的值 // Or do it on one line. row.createCell((short)1).setCellvalue(1.2); //设置cell浮点类型的值 row.createCell((short)2).setCellvalue("test"); //设置cell字符类型的值 row.createCell((short)3).setCellvalue(true); //设置cell布尔类型的值 HSSFCellStyle cellStyle = wb.createCellStyle(); //建立新的cell样式 cellStyle.setDataFormat (HSSFDataFormat.getFormat("m/d/yy h:mm")); //设置cell样式为定制的日期格式 HSSFCell dCell =row.createCell((short)4); dCell.setCellvalue(new Date()); //设置cell为日期类型的值 dCell.setCellStyle(cellStyle); //设置该cell日期的显示格式 HSSFCell csCell =row.createCell((short)5); csCell.setEncoding(HSSFCell.ENCODING_UTF_16); //设置cell编码解决中文高位字节截断 csCell.setCellvalue("中文测试_Chinese Words Test"); //设置中西文结合字符串 row.createCell((short)6).setCellType (HSSFCell.CELL_TYPE_ERROR); //建立错误cell // Write the output to a file FileOutputStream fileOut = new FileOutputStream("workbook.xls"); wb.write(fileOut); fileOut.close(); } }
在Java中读写Excel文件
最新推荐文章于 2021-11-23 10:59:18 发布