开发中经常会设计到excel的处理,如导出Excel,导入Excel到数据库中
首先我们先见到了解一下什么是Apache POI
**Apache POI 简介是用Java编写的免费开源的跨平台的 Java API,Apache POI提供API给Java程式对Microsoft Office(Excel、WORD、PowerPoint、Visio等)格式档案读和写的功能
Apache POI常用的类**
HWPF - 提供读写Microsoft Word DOC97格式档案的功能XWPF - 提供读写Microsoft Word DOC2003格式档案的功能HSLF - 提供读写Microsoft PowerPoint格式档案的功能HDGF - 提供读Microsoft Visio格式档案的功能HPBF - 提供读Microsoft Publisher格式档案的功能:HSMF - 提供读Microsoft Outlook格式档案的功能在开发中我们经常使用HSSF用来操作Excel处理表格数据,对于其它的不经常使用。
Excel中的工作簿、工作表、行、单元格中的关系:
一个Excel文件对应于一个workbook(HSSFWorkbook)一个workbook可以有多个sheet(HSSFSheet)组成一个sheet是由多个row(HSSFRow)行组成一个row是由多个cell(HSSFCell)列组成下面我简单编写一个Demo,在电脑桌面创建一个Excel
@Test public void createExcel() throws IOException { FileSystemView fsv = FileSystemView.getFileSystemView(); String desktop = fsv.getHomeDirectory().getPath(); String filePath = desktop + "/template.xls"; File file = new File(filePath); OutputStream outputStream = new FileOutputStream(file); HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet sheet = workbook.createSheet("Sheet1"); HSSFRow row = sheet.createRow(0); row.createCell(0).setCellValue("id"); row.createCell(1).setCellValue("序列号"); row.createCell(2).setCellValue("时间"); row.createCell(3).setCellValue("个数"); row.createCell(4).setCellValue("单价"); row.createCell(5).setCellValue("金额"); row.setHeightInPoints(30); // 设置行的高度 HSSFRow row1 = sheet.createRow(1); row1.createCell(0).setCellValue("1"); row1.createCell(1).setCellValue("NO00001"); // 日期格式化 HSSFCellStyle cellStyle2 = workbook.createCellStyle(); HSSFCreationHelper creationHelper = workbook.getCreationHelper(); cellStyle2.setDataFormat(creationHelper.createDataFormat().getFormat("yyyy-MM-dd HH:mm:ss")); sheet.setColumnWidth(2, 20 * 256); // 设置列的宽度 HSSFCell cell2 = row1.createCell(2); cell2.setCellStyle(cellStyle2); cell2.setCellValue(new Date()); row1.createCell(3).setCellValue(2); // 保留两位小数 HSSFCellStyle cellStyle3 = workbook.createCellStyle(); cellStyle3.setDataFormat(HSSFDataFormat.getBuiltinFormat("0.00")); HSSFCell cell4 = row1.createCell(4); cell4.setCellStyle(cellStyle3); cell4.setCellValue(29.5); // 货币格式化 HSSFCellStyle cellStyle4 = workbook.createCellStyle(); HSSFFont font = workbook.createFont(); font.setFontName("华文行楷"); font.setFontHeightInPoints((short)15); font.setColor(HSSFColor.RED.index); cellStyle4.setFont(font); HSSFCell cell5 = row1.createCell(5); cell5.setCellFormula("D2*E2"); // 设置计算公式 // 获取计算公式的值 HSSFFormulaEvaluator e = new HSSFFormulaEvaluator(workbook); cell5 = e.evaluateInCell(cell5); System.out.println(cell5.getNumericCellValue()); workbook.setActiveSheet(0); workbook.write(outputStream); outputStream.close(); }我不能保证我所说的都是对的,但我能保证每一篇都是用心去写的,我始终认同: “分享的越多,你的价值增值越大”,我们一同在分享中进步,在分享中成长,越努力越幸运。再分享一句话“十年前你是谁,一年前你是谁,甚至昨天你是谁,都不重要。重要的是,今天你是谁,以及明天你将成为谁。” 人生赢在转折处,改变从现在开始! 支持我的朋友们记得点波推荐哦,您的肯定就是我前进的动力。 作者:T,Joker.田总 微信公众号:田爸爸服务号 有事Q我:1728569609 后期我会将交流群分享出来 本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。