使用Java导出Excel案例详解

package com.wy.common.util;

import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.hssf.util.Region;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;

//这是一个导出Excel的工具类
public class ExportExcelUtils{
/**
* 这是一个通用的方法,将一个map集合作为表格内容输入到excel中
*
* @param title
* 表格标题名
* @param headers
* 表格属性列名数组
* @param rows
* 需要显示的数据集合,row为List
* @param rowkeys
* 与headers对应的map的key的集合数组
* @param conditionsDescrip
* xls说明
* @param out
* 与输出设备关联的流对象,可以将EXCEL文档导出到本地文件或者网络中
*/

@SuppressWarnings("deprecation")
public void exportExcel(String title, String[] headers,List<Map> rows, String[] rowkeys, OutputStream out) {
    // 声明一个工作薄
    HSSFWorkbook workbook = new HSSFWorkbook();
    // 生成一个表格
    HSSFSheet sheet = workbook.createSheet(title);
    // 设置表格默认列宽度为15个字节
    sheet.setDefaultColumnWidth((short) 25);
    if(rows!=null && rows.size()>0 ){
        //判断传入集合数据,如为空即不填充数据导出空Excel
        /** ----------- 生成标题     ------------*/
        //第一行写入标题
        HSSFFont fontTitle = workbook.createFont();
        HSSFCellStyle titleStyle = workbook.createCellStyle();
        titleStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        titleStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        fontTitle.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        fontTitle.setFontHeightInPoints((short) 16);
        titleStyle.setFont(fontTitle);
        if(headers!=null){
            //这里作非空验证
            sheet.addMergedRegion(new Region(0,(short)0,0,(short)(headers.length-1)));
        }
        HSSFRow rowTitle = sheet.createRow(0);
        rowTitle.setHeight((short)500);
        HSSFCell cellTitle = rowTitle.createCell(0);
        cellTitle.setCellStyle(titleStyle);
        cellTitle.setCellValue(title);

        /** ----------- 生成表头     ------------*/
        HSSFFont fontHeader = workbook.createFont();
        fontHeader.setBoldweight(Font.BOLDWEIGHT_BOLD);
        HSSFCellStyle cstyleHeader =workbook.createCellStyle();
        cstyleHeader.setFont(fontHeader);
        cstyleHeader.setAlignment(CellStyle.ALIGN_CENTER);
        cstyleHeader.setBorderBottom(CellStyle.BORDER_THIN);
        cstyleHeader.setBorderLeft(CellStyle.BORDER_THIN);
        cstyleHeader.setBorderRight(CellStyle.BORDER_THIN);
        cstyleHeader.setBorderTop(CellStyle.BORDER_THIN);
        HSSFRow row = sheet.createRow(1);
        for (short i = 0; i < headers.length; i++) {
            HSSFCell cell = row.createCell(i);
            //cell.setCellStyle(style);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellStyle(cstyleHeader);
            cell.setCellValue(text);
        }

        /** ----------- 生成数据行     ------------*/
        int index = 2;
        HSSFFont fontData = workbook.createFont();
        fontData.setBoldweight(Font.BOLDWEIGHT_NORMAL);
        HSSFCellStyle cstyleData =workbook.createCellStyle();
        cstyleData.setBorderBottom(CellStyle.BORDER_THIN);
        cstyleData.setBorderLeft(CellStyle.BORDER_THIN);
        cstyleData.setBorderRight(CellStyle.BORDER_THIN);
        cstyleData.setBorderTop(CellStyle.BORDER_THIN);
        cstyleData.setFont(fontData);
        cstyleData.setAlignment(CellStyle.ALIGN_CENTER);

        /*      HSSFCellStyle cstyleData1 =workbook.createCellStyle();
        cstyleData1.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        cstyleData1.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        cstyleData1.setBorderRight(HSSFCellStyle.BORDER_THIN);
        cstyleData1.setBorderTop(HSSFCellStyle.BORDER_THIN);
        cstyleData1.setFont(fontData);
        cstyleData1.setAlignment(HSSFCellStyle.ALIGN_LEFT);*/
        for(Map row1 : rows){
            row = sheet.createRow(index);
            //获取map的所有需要导入到excel中数据key值
            for(int i = 0 ; i < rowkeys.length ; i++){
                HSSFCell cell = row.createCell(i);
                cell.setCellStyle(cstyleData);
                String key = rowkeys[i];
                String cellValue="";
                if(row1.get(key)!=null){
                    cellValue =row1.get(key).toString();
                }
                else{
                    cellValue="";
                }
                cell.setCellValue(cellValue);
            }
            index++;
        }

        /** ----------- 生成说明行     ------------*/
        HSSFFont fontDesc = workbook.createFont();
        HSSFCellStyle descStyle =workbook.createCellStyle();
        descStyle.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index);
        descStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
        descStyle.setAlignment(CellStyle.ALIGN_LEFT);
        descStyle.setVerticalAlignment(CellStyle.VERTICAL_TOP);
        fontDesc.setFontHeightInPoints((short) 9);
        descStyle.setFont(fontDesc);

        //最后行写入描述
        /*
        sheet.addMergedRegion(new Region(index,(short)0,index,(short)(headers.length-1)));
        HSSFRow rowDesc = sheet.createRow(index);
        rowDesc.setHeight((short)1500);
        HSSFCell cellDesc = rowDesc.createCell(0);
        cellDesc.setCellStyle(descStyle);
        descStyle.setWrapText(true);
        cellDesc.setCellValue(new HSSFRichTextString(conditionsDescrip));
         */
    }
    try {
        workbook.write(out);
    } catch (IOException e) {
        e.printStackTrace();
    }

}

}

/*Action层中的方法*/
public String exportQuesByTypeAndId(){
        try {

            ExportExcelUtils<T> ex = new ExportExcelUtils<T>();
            ByteArrayOutputStream bos = new ByteArrayOutputStream();

            // 获取查询数据
            List<Map> rows = null;
            String questionnaireId = ServletActionContext.getRequest().getParameter("questionnaireId");
            TbInteractionQuestionnaire tbQuestionnaire=(TbInteractionQuestionnaire) questionnaireService.getDataBaseDao().load(TbInteractionQuestionnaire.class, questionnaireId);
            String type=ServletActionContext.getRequest().getParameter("type");
            rows = questionnaireService.exportQuesByTypeAndId(questionnaireId,type);
            int i=0;
            String name=tbQuestionnaire.getQuestionnaireTitle()+"_参与人员_"+DataConvertUtil.getCurrentDate();
            if(rows!=null && rows.size()>0 && rows.get(0)!=null){
            //headers 表示excel首行标题
                String[] headers =new String[rows.get(0).size()];
            //rowkeys 表示excel填充数据行对应的key
                String[] rowkeys =new String[rows.get(0).size()];
                System.out.println(rows.size());
                Iterator ita = rows.get(0).entrySet().iterator(); 
                while(ita.hasNext()){
                    /*这里面我将数据库查询出的数据字段名称
                    替换成对应中文作为Excel每列标题,将字段
                    名称直接作为数据行的key,分别将标题和
                    key存放在数组中,这里大家可以自定义
                    Excel的每列标题,key可以直接取库中
                    字段名称。
                    */
                    Entry entry = (Entry)ita.next();
                    headers[i]=entry.getKey().toString().replaceAll("userAccount","工号/学号").replaceAll("orgName","部门").replaceAll("persontype", "类别").replaceAll("voteFlag","参与状态");
                    rowkeys[i]=entry.getKey().toString();
                    i++;
                }
                ex.exportExcel(name, headers, rows, 
                rowkeys,bos);
            }
            else{
                /*
                这里当数据集为空则传入null,
                输出流对象必输传
                */
                ex.exportExcelNoAnswerForQues(name             
                    ,null, null,null,bos);
            }
            byte[] fileBytes = bos.toByteArray();
            ByteArrayInputStream bis = new ByteArrayInputStream(fileBytes);
            bos.close();
            inputStream = bis;
            //这里fileName指定为文件的名称(全局变量需要给出相应的getter,setter方法)
            fileName = new String((name + ".xls").getBytes(),"ISO-8859-1");
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            rspCode = RtnCodeConstant.RTN_CODE_UNKNOW_ERROR;
            e.printStackTrace();
        }
        return SUCCESS;
    }

//这里是struts的配置

<action name="exportQuesByTypeAndId"
   class="queryQuertionnaireAction" 
        method="exportQuesByTypeAndId">
    <result type="stream">
        <param name="noCache">true</param>
        <param name="contentType">application/octet-stream</param>
        <param name="inputName">inputStream</param>
        <param name="contentDisposition">attachment;filename="${fileName}"</param>
        <param name="bufferSize">false</param>
    </result>
    <result      name="noSession">/jsps/login/no_session.jsp
    </result>
</action>

//下图为数据库 中查询的数据
数据库中查询的数据

//注:导出excel需通过location.href 的方式直接请求后台方法,或者使用表单提交方式
导出excel结果图

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
以下是一个简单的Java导出Excel的示例: 1. 首先,需要添加poi和poi-ooxml依赖: ```xml <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.17</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.17</version> </dependency> ``` 2. 创建一个工具类来导出Excel: ```java import java.io.FileOutputStream; import java.io.IOException; import java.util.List; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFCellStyle; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ExcelUtil { public static void export(List<Object[]> data, String fileName) throws IOException { XSSFWorkbook workbook = new XSSFWorkbook(); XSSFSheet sheet = workbook.createSheet("Sheet1"); // 设置表头 XSSFRow headerRow = sheet.createRow(0); String[] headers = {"Name", "Age", "Gender"}; for (int i = 0; i < headers.length; i++) { XSSFCell cell = headerRow.createCell(i); cell.setCellValue(headers[i]); } // 填充数据 int rowNum = 1; for (Object[] row : data) { XSSFRow dataRow = sheet.createRow(rowNum++); for (int i = 0; i < row.length; i++) { XSSFCell cell = dataRow.createCell(i); cell.setCellValue(row[i].toString()); } } // 格式化单元格 XSSFCellStyle cellStyle = workbook.createCellStyle(); cellStyle.setWrapText(true); for (int i = 0; i < headers.length; i++) { sheet.autoSizeColumn(i); sheet.setColumnWidth(i, sheet.getColumnWidth(i) + 500); for (Row row : sheet) { Cell cell = row.getCell(i); if (cell != null) { cell.setCellStyle(cellStyle); } } } // 导出Excel FileOutputStream outputStream = new FileOutputStream(fileName); workbook.write(outputStream); outputStream.close(); } } ``` 3. 在主函数中调用导出方法: ```java import java.io.IOException; import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) throws IOException { // 准备数据 List<Object[]> data = new ArrayList<>(); data.add(new Object[]{"Tom", 20, "Male"}); data.add(new Object[]{"Lily", 22, "Female"}); data.add(new Object[]{"Lucy", 21, "Female"}); // 导出Excel ExcelUtil.export(data, "output.xlsx"); } } ``` 以上示例演示了如何使用Java导出Excel文件。实际上,Excel导出的实现方式还有很多,可以根据具体需求选择合适的方法。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zsw_sh

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值