java 导出excls(springBoot + myBatis+maven)

版权声明:原创不易,转载请注明出处,谢谢!!! https://blog.csdn.net/Java_monkeys/article/details/81540942

仅供大家参考,如内容中有不对的地方请大家谅解,并指出,我会及时改正,谢谢!!!

java 导出Excls的方法(此方法比较简单的,好操作的方法)

1.在pom.xml文件中加入如下代码:

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>${poi.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>${poi.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml-schemas</artifactId>
            <version>${poi.version}</version>
        </dependency>

2.导出excel的工具类方法

下边代码中exportExcel方法中的各个参数含义:

1.list是需要导出数据的集合;

2.filePath是模板文件的位置;

3.title excel的标题;

4.beginRow导出数据在表格中的开始行数;

HSSFWorkbook     excel的文档对象

HSSFSheet            excel的表单

HSSFRow               excel的行

HSSFCell                excel的格子单元

扫描二维码关注公众号,回复: 5027651 查看本文章

HSSFFont               excel字体

HSSFCellStyle         cell样式

public class ExportExcel
{

    public static void exportExcel(HttpServletResponse response, List<Map<String, Object>> list,
                                   String filePath, String title, int beginRow)
        throws IOException
    {
        HSSFSheet sheet = null;
        HSSFRow row = null;
        HSSFCell cell = null;
        HSSFCellStyle style = null;
        HSSFWorkbook workbook = null;
        try
        {
            workbook = new HSSFWorkbook(new FileInputStream(filePath));
            sheet = workbook.getSheetAt(0);
        }
        catch (IOException e1)
        {
            response.getWriter().write("模板不存在");
            return;
        }
        for (int i = 0; i < beginRow; i++ )
        {
            row = sheet.getRow(i);
            for (int j = 0; j < row.getPhysicalNumberOfCells(); j++ )
            {
                cell = row.getCell((short)j);
                cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                if (cell.getStringCellValue() != null
                    && cell.getStringCellValue().indexOf("{title}") > -1)
                {
                    cell.setCellValue(cell.getStringCellValue().replaceAll("\\{title\\}", title));
                }
            }
        }

        try
        {
            style = sheet.getRow(beginRow).getCell((short)0).getCellStyle();
            style.setWrapText(true);
            for (int i = 0; i < list.size(); i++ )
            {
                row = sheet.createRow((int)i + beginRow);
                HashMap<String, String> map = (HashMap)list.get(i);
                int j = 0;
                for (String key : map.keySet())
                {
                    cell = row.createCell((short)j, HSSFCellStyle.ALIGN_CENTER);
                    cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                    cell.setCellValue(toEmpty(String.valueOf(map.get(key))));
                    cell.setCellStyle(style);
                    j += 1;
                }
            }
            ServletOutputStream output = response.getOutputStream();
            try
            {
                response.reset();
                response.setContentType("application/vnd.ms-excel;charset=utf-8");
                response.setHeader("Content-Disposition",
                    "attachment;filename=" + new String((title + ".xls").getBytes(),
                        "iso-8859-1"));
                // out.clear(); //清空缓存的内容。
                // out = pageContext.pushBody(); //参考API
                workbook.write(output);
                output.flush();
                output.close();
            }
            catch (Exception e)
            {
                response.getWriter().write("导出失败");
            }
            finally
            {
                output.close();
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
            response.getWriter().write("导出失败");
        }
    }
}

2.在controller中调用的工具类方法

@RequestMapping(value = {"exportExcel"})
    public void exportExcel(TOtherItem tOtherItem, HttpServletRequest request,
                            HttpServletResponse response)
    {
        String zd = request.getParameter("zd");
        String dd = request.getParameter("dd");
        String officeSql = QueryUtils.querySql(zd, dd, "a", "officeid");
        tOtherItem.getSqlMap().put("officeSql", officeSql);
        tOtherItem.getSqlMap().put("stime", request.getParameter("stime"));
        tOtherItem.getSqlMap().put("etime", request.getParameter("etime"));
        List<TOtherItem> list = otherItemService.findList(tOtherItem);
        List dataList = new ArrayList();
        int i = 1;
        for (TOtherItem oi : list)
        {
            //向excls中每一列插入数据
            dataList.add(mapTemp);
        }
        try
        {
            String os = System.getProperties().getProperty("os.name");
            String filepath = this.getClass().getClassLoader().getResource(
                "/excel/otherItem.xls").getPath();
            if (filepath != null && filepath.indexOf("/") == 0
                && os.toLowerCase().startsWith("win"))
            {
                filepath = filepath.substring(1, filepath.length());
            }
            //调用工具类方法,5代表excls开始的行
            ExportExcel.exportExcel(response, dataList, filepath, "XXXX-日常巡查-其他事项日志", 5);
        }
        catch (Exception e)
        {
            logger.error("其他事项日志Excel失败--" + e.getMessage(), e);
        }
    }

3.制作一个对应的excls表格(xls、xlsx)

xls是office2003的后缀,xlsx是office2007的后缀,我这里用的xls(xls跟xlsx的行数有区别)

猜你喜欢

转载自blog.csdn.net/Java_monkeys/article/details/81540942