java excel导出(POI)

需要引入的jar包:

      <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.16</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.16</version>
        </dependency>

1、前端

$(‘#exportBtn‘).on(‘click‘, function () {
    var hasChecked = $(‘input[name=clientOption]‘).is(‘:checked‘);
    if (!hasChecked) {
        $.tip({text: ‘请至少选择一个!‘, status: ‘confirm‘});return;
    }
    var values = [];
    $(‘input[name=clientOption]:checked‘).each(function () {
        values.push($(this).val());
    })
    location.href = ‘/admin/export?values=‘ + values;
})

2、后端接收,并生成原始的List数据

  @RequestMapping(value = "export")
    public void exportClient(String[] values, HttpServletResponse response) {
        try {
            String title = "Title";
            Map<Integer, String> headerMap = new LinkedHashMap<>(3);
            headerMap.put(0, "Header0");
            headerMap.put(1, "Header1");
            headerMap.put(2, "Header2");
            List<List<String>> contentList = new ArrayList<>();
            for (int index = 0; index < values.length; index++) {
                List<String> cellList = new ArrayList<>();
                contentList.add(values[index]);
            }
            ExcelHelper.downloadExcel(response, title, headerMap, contentList);
        } catch (Exception e) {
            // todo
        }
    }

3、下载

  public static void downloadExcel(HttpServletResponse response, String title, Map<Integer, String> headerMap, List<List<String>> contentList) {
        try {
            // 内容写入Excel
            XSSFWorkbook workbook = ExcelHelper.writeToExcel(title, headerMap, contentList);
            // workbook写入到输出流中
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            workbook.write(os);
            // 设置response参数,打开下载页面
            response.reset();
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + new String((title + DateUtils.toDateText(new Date(), DateUtils.NUMBER_TIME_FORMAT) + ".xlsx").getBytes(), CHARSET_ISO_8859_1));
            byte[] content = os.toByteArray();
            InputStream is = new ByteArrayInputStream(content);
            ServletOutputStream out = response.getOutputStream();
            BufferedInputStream bis = new BufferedInputStream(is);
            BufferedOutputStream bos = new BufferedOutputStream(out);
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
            // 关闭输入输出流
            bis.close();
            bos.close();
            out.flush();
            out.close();
        } catch (Exception e) {
            // todo
        }
    }

4、List写入到Excel对象中

  public static XSSFWorkbook writeToExcel(String title, Map<Integer, String> headerMap, List<List<String>> contentList) {
        XSSFWorkbook workbook = new XSSFWorkbook();
        try {
            XSSFSheet sheet = workbook.createSheet(title);
            // excel样式设置
            XSSFCellStyle titleStyle = workbook.createCellStyle();
            titleStyle.setAlignment(HorizontalAlignment.CENTER);
            Font titleFont = workbook.createFont();
            titleFont.setFontHeightInPoints((short) 12);
            titleFont.setFontName("Microsoft YaHei");
            titleFont.setBold(true);
            titleStyle.setFont(titleFont);

            // 写入标题
            XSSFRow row0 = sheet.createRow(0);
            XSSFCell row0cell0 = row0.createCell(0);
            row0cell0.setCellValue(title);
            row0cell0.setCellStyle(titleStyle);
            // excel合并单元格
            CellRangeAddress region = new CellRangeAddress(0, 0, 0, headerMap.size() - 1);
            sheet.addMergedRegion(region);

            //写入主体内容
            for (int rowIndex = 0; rowIndex < contentList.size(); rowIndex++) {
                XSSFRow rows = sheet.createRow(rowIndex + 2);
                List<String> rowList = contentList.get(rowIndex);
                for (int cellIndex = 0; cellIndex < rowList.size(); cellIndex++) {
                    rows.createCell(cellIndex).setCellValue(rowList.get(cellIndex));
                }
            }

            // 写入头部列
            XSSFRow row1 = sheet.createRow(1);
            for (int headerIndex = 0; headerIndex < headerMap.size(); headerIndex++) {
                row1.createCell(headerIndex).setCellValue(headerMap.get(headerIndex));
          // sheet.autoSizeColumn(headerIndex, true);
                sheet.setColumnWidth(headerIndex, row1.getCell(headerIndex).toString().getBytes().length * 3 * 256);
            }
        } catch (Exception e) {
            // todo
        }
        return workbook;
    }

参考链接:

http://blog.csdn.net/renlei0109/article/details/36906409 http://bbs.csdn.net/topics/391888713?page=1

http://www.jb51.net/article/87574.htm

http://www.cnblogs.com/crazyapple/p/5489588.html

http://blog.csdn.net/houxuehan/article/details/50960259

http://blog.csdn.net/lp1791803611/article/details/52351333

http://yjck.iteye.com/blog/1609232

时间: 2025-01-01 23:14:54

java excel导出(POI)的相关文章

java excel导出

1.  Excel导出的核心方法在ExportExcel类中,使用时请将该类完整的引入. 1 import java.io.IOException; 2 import java.io.OutputStream; 3 import java.lang.reflect.Field; 4 import java.lang.reflect.InvocationTargetException; 5 import java.lang.reflect.Method; 6 import java.text.Si

Java 通过Xml导出Excel文件,Java Excel 导出工具类,Java导出Excel工具类

Java 通过Xml导出Excel文件,Java Excel 导出工具类,Java导出Excel工具类 ============================== ?Copyright 蕃薯耀 2017年9月13日 http://www.cnblogs.com/fanshuyao/ 直接上代码: import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.ref

Excel导出POI

CwReportExcleUtils.java 类 1 package com.bigdata.campus.report.utils; 2 3 import java.util.List; 4 import java.util.Map; 5 6 import org.apache.poi.hssf.usermodel.HSSFWorkbook; 7 import org.apache.poi.ss.usermodel.Cell; 8 import org.apache.poi.ss.userm

java excel导出(表头合并,多行表头)

@RequestMapping(value="orderExcelList2") public void orderExcelList2forJava(Order order,HttpServletResponse response){ Map<String,Object> map = toOrderExcelJSONList2(order); List<Bottle> bottleList = (List<Bottle>) map.get(&quo

在做excel导出时如何将workbook直接写在输出流中

参考网址 https://blog.csdn.net/u011109420/article/details/51330677 https://blog.csdn.net/u012116457/article/details/49780677 Java 后台 Excel 文件生成后转化为字节流 java excel 使用 poi组件, HSSFWorkbook workBook = new HSSFWorkbook(); 对于workBook生成字节流,很容易发现有个workBook .getBy

java 通过Apache poi导出excel代码demo实例

package com.zuidaima.excel.util; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.

java中使用poi导入导出excel文件_并自定义日期格式

Apache POI项目的使命是创造和保持java API操纵各种文件格式基于Office Open XML标准(OOXML)和微软的OLE复合文档格式(OLE2)2.总之,你可以读写Excel文件使用java.此外,您可以读取和写入MS Word和PowerPoint文件使用java.Apache POI是java Excel解决方案(Excel 97-2008). 需要jar: poi-3.9-20121203.jar 导出 public static void main(String[]

Excel导出学习之道:Java Web利用POI导出Excel简单例子

采用Spring mvc架构: Controller层代码如下 [java] view plaincopy @Controller public class StudentExportController{ @Autowired private StudentExportService studentExportService; @RequestMapping(value = "/excel/export") public void exportExcel(HttpServletReq

java excel poi导出问题

1.每次打开excel就会提示:"此文件中某些文本格式可能已经更改,因为它已经超出最多允许的字体数.关闭其他文档再试一次可能有用." 解决办法:是因为创建的字体太多了,当调用HSSFWorkbook的createFont之后就创建一种字体,就算字体属性完全一样也是要创建一个新字体对象的: 而创建的数目是有限的,因此不要频繁调用HSSFWorkbook的createFont方法, 把创建的font缓存起来,相同字体属性的就不要再create了 粘贴的内容中由于格式或数据问题,可能引发了E