java采取poi处理excel

    xiaoxiao2025-02-02  11

    前言

    平时需要处理excel文件,一般有2种选择:apache的poi和jxl。jxl一般对文件处理支持不太好,主要还是使用poi更多一些。做个简单介绍。 注:含jxls的简单处理

    简介poi

    poi可以处理excel文件,同时还能处理word和ppt文件。可从apache官网进行查看。以下的内容均为官网所得。 处理excel时,有HSSF、XSSF等区别。简单就是HSSF支持excel97等以后,XSSF支持excel2007等以后。具体可以搜索查看excel区别和HSSF、XSSF区别。

    HSSF是POI工程对Excel 97(-2007)文件操作的纯Java实现 XSSF是POI工程对Excel 2007 OOXML (.xlsx)文件操作的纯Java实现 POI 3.8版本开始,提供了一种基于XSSF的低内存占用的API—-SXSSF

    项目依赖maven

    poi一般依赖几个文件,poi、poi-ooxml、poi-schemas等等。具体版本可去maven仓库查询。 maven依赖如下:

    <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.1.4</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.1.4</version> </dependency> <dependency> <groupId>net.sf.jxls</groupId> <artifactId>jxls-core</artifactId> <version>1.0.5</version> </dependency>

    概述

    以下是简单的写入/写出excel例子:

    // Workbook wb = WorkbookFactory.create(inputStream); Workbook wb = new HSSFWorkbook(); //new XSSFWorkbook(); Sheet sheet = wb.createSheet("new sheet"); //sheet = excel的工作表 Row row = sheet.createRow(0); //row = excel的行 Cell cell = row.createCell(0); //cell = 单元格 cell.setCellValue(123); // 设置值 FileOutputStream fileOut = new FileOutputStream("workbook.xls"); wb.write(fileOut); fileOut.close();

    直接可以运行,很好理解。还有其他的很多地方,都是基于此补充。 1.Cell可以设置样式,使用CellStyle进行设置。

    Cell cell = row.createCell(column); cell.setCellValue("Align It"); CellStyle cellStyle = wb.createCellStyle(); cellStyle.setAlignment(halign); cellStyle.setVerticalAlignment(valign); cell.setCellStyle(cellStyle);

    2.Cell可以设置字体颜色。

    // Create a new font and alter it. Font font = wb.createFont(); font.setFontHeightInPoints((short)24); font.setFontName("Courier New"); font.setItalic(true); font.setStrikeout(true); // Fonts are set into a style so create a new one to use. CellStyle style = wb.createCellStyle(); style.setFont(font);

    3.创建Workbook时,可采取直接创建或WorkFactory创建,建议第二种。第二种会进行判断,采取哪种方式创建。

    Workbook wb = WorkbookFactory.create(inputStream); Workbook wb = new HSSFWorkbook(); //new XSSFWorkbook();

    4.对于有些地方的使用可能还需要createionHelper处理。

    CreationHelper creationHelper = wb.getCreationHelper(); //wb = Wookbook

    5.单列、单行可以进行隐藏操作

    sheet.setColumnHidden(2,true); row.setZeroHeight(true);

    6.可以设置全局的宽高,不过试过,excel导出会有问题。可以参考下。

    /** * 设置全局默认的Sheet样式 * 注:一旦设置了这些属性,如果某一行或者某一列没有设置宽度,就会使用默认宽度或高度 * * @param sheet * @param defaultWeight 参数的单位是1/256个字符宽度,也就是说,所有设置的宽度需要*256 * @param defaultHeight 参数的单位是1/20个点,也就说,所有的设置宽度需要*20 */ public static void setDefaultSheet(Sheet sheet, int defaultWeight, int defaultHeight) { sheet.setDefaultColumnWidth(defaultWeight * 256); sheet.setDefaultRowHeight((short) (defaultHeight * 20)); // sheet.setDefaultRowHeightInPoints(); //默认是点,单位是height的20倍 }

    注:部分代码样式如下

    Font font = workbook.createFont(); font.setFontHeightInPoints((short) 11); // 将字体大小设置为**px font.setFontName("宋体"); font.setColor(IndexedColors.GREEN.getIndex()); CellStyle cellStyle = workbook.createCellStyle(); cellStyle.setFont(font); cellStyle.setAlignment(CellStyle.ALIGN_CENTER); cellStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER); cellStyle.setFillForegroundColor(IndexedColors.LIGHT_GREEN.getIndex()); cellStyle.setFillPattern(CellStyle.SOLID_FOREGROUND); cellStyle.setBorderBottom(CellStyle.BORDER_THIN); cellStyle.setBorderLeft(CellStyle.BORDER_THIN); cellStyle.setBorderRight(CellStyle.BORDER_THIN);

    基本的使用就是以上了,对于详细的可参考apache的poi的介绍。有对于部分细节的说明。 地址:https://poi.apache.org/spreadsheet/quick-guide.html

    简介jxls

    当需要输出一定格式的excel样式时,我们可能需要指定输出的格式,多少行,多少列,数据如何存放等等。而这些操作一般特别繁琐。需要我们不断循环进行,最后才能输出看着还算美观的excel样式(包含数据)。 采取jxls,就能根据提前制作好的excel样式直接填充我们需要的数据,特别方便快速,可以学习下。 项目依赖如上所述。

    概述

    一般我们需要向一些模版塞入不少数据,而这些模版需要进行简单设计。如下:

    这里抛去代码,需要设计好id,名称,还有下面的单元格样式等等。这些设计繁琐了,采取如下jxls代码,就能简单进行代码的填充处理了。详细参考官网

    public static InputStream makeReportFromTemplet(String templateFileName, Map beans) { Configuration config = new Configuration(); XLSTransformer transformer = new XLSTransformer(config); InputStream is = null; InputStream excelStream = null; Workbook workBook = null; try { is = new FileInputStream(templateFileName); try { workBook = transformer.transformXLS(is, beans); } catch (ParsePropertyException e) { e.printStackTrace(); } catch (InvalidFormatException e) { e.printStackTrace(); } // 产生POI输出流 ByteArrayOutputStream os = new ByteArrayOutputStream(); workBook.write(os); excelStream = new ByteArrayInputStream(os.toByteArray()); is.close(); } catch (IOException ie) { ie.printStackTrace(); } return excelStream; }

    参数:templateFileName 就是提前设计好的空白的excel样式,beans就是需要填充的数据。 beans数据:

    Map<String, Object> beans = new HashMap<String, Object>(); User user1 = new User(); user1.setId(1L); user1.setName("aaa"); User user2 = new User(); user2.setId(2L); user2.setName("bbb"); List<User> list = new ArrayList<User>(); list.add(user1); list.add(user2);

    最后将结果输出到指定文件即可。效果如下:

    无需设计样式,即可展示出数据。至于excel中添加的代码,可参考官网说明。(翻墙突然不成功了,不罗列了)

    常见标签

    1.<jx:forEach var=" ? " varStatus="status"> </jx:forEach> 注:用于迭代, 属性是var;varStatus待确定 2. <jx:if test="${ ? }" > </jx:if> 注:用于逻辑判断, 有一个属性test 3. $[sum(position)] 注:求和 4. $[min(position)] 注:求最大值 5. $[max(position)] 注:求最小值 6. $[average(position)] 注:求平均值 7. $[count(position)] 注:求数量

    异常

    1.采取poi下载excel时,部分浏览器会报错,如下:

    ClientAbortException: java.net.SocketException: Software caused connection abort: socket write error at org.apache.catalina.connector.OutputBuffer.realWriteBytes(OutputBuffer.java:388) at org.apache.tomcat.util.buf.ByteChunk.flushBuffer(ByteChunk.java:462) at org.apache.catalina.connector.OutputBuffer.doFlush(OutputBuffer.java:334) at org.apache.catalina.connector.OutputBuffer.close(OutputBuffer.java:283) at org.apache.catalina.connector.CoyoteOutputStream.close(CoyoteOutputStream.java:108)

    暂时发现出现在部分浏览器上面,原因未知,待查看。


    参考: http://blog.csdn.net/zdp072/article/details/30310473

    转载请注明原文地址: https://ju.6miu.com/read-1296020.html
    最新回复(0)