javaSE中的数据导出到Excel表、javaEE中后台生成Excel文件到浏览器端下载

28 篇文章 0 订阅

整个项目中导出数据到.Excel的源码


 import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import Vo.SellAnimal;

public class FileUtils {
    public static final String SEPARATE_FIELD = ",";// 逗号分隔符
    public static final String SEPARATE_LINE = "\r\n";// 行分隔符

    public static void saveAniaml(SellAnimal animal) {
        Date data = new Date(); // 获取系统时间
        SimpleDateFormat fmort = new SimpleDateFormat("yyyyMMdd");// 注时间格式
        String time = "销售记录" + fmort.format(data) + ".csv";
        InputStream in = null; // 输入流,读取文件的内容
        try {
            in = new FileInputStream(time);//向上转型
            if (in != null) {
                in.close();
                creatfile(time, true, animal);// 在已有文件的后面接着写
            }

        } catch (FileNotFoundException e) {
            creatfile(time, false, animal);// 创建新的文件

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void creatfile(String time, boolean object, SellAnimal animal) {
        // TODO Auto-generated method stub
        BufferedOutputStream out = null;// 字节缓冲流
        StringBuffer str = new StringBuffer();
        try {
            if (object) {
                out = new BufferedOutputStream(new FileOutputStream(time, true));
            } else {
                out = new BufferedOutputStream(new FileOutputStream(time));
                String[] filesort = { "宠物名称", "宠物编号", "宠物品种", "宠物数量", "宠物单价(/元)", "总价" };
                for (String fieldKey : filesort) {
                    str.append(fieldKey).append(SEPARATE_FIELD);
                }
            }
            str.append(SEPARATE_LINE);
            str.append(animal.getName()).append(SEPARATE_FIELD);
            str.append(animal.getNum()).append(SEPARATE_FIELD);
            str.append(animal.getPin()).append(SEPARATE_FIELD);
            str.append(animal.getShu()).append(SEPARATE_FIELD);
            str.append(animal.getPrice()).append(SEPARATE_FIELD);
            str.append(animal.getMoney()).append(SEPARATE_FIELD);
            String str1 = str.toString();
            byte[] shu = str1.getBytes();
            for (int i = 0; i < shu.length; i++) {
                out.write(shu[i]);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}


--------------------------------------
2019-7-16    在我做的ssm项目中又有了导出文件的需求且这次比较复杂,需要有四层的标题,大标题小标题什么的,先放源码:然后说用到的jar包是poi-3.10;这个自己去官网上找,jar的版本太高的话不支持此源代码,因为有的版本更新了某些变量导致jar包里面根本就没有此源码的某些方法,这里主要放的是Excel的表格样式还有下载的代码,表格中具体信息由于某种原因进行了删减


/**
     * excel自定义导出
     * @param hAqscTieupsummary
     * @param request
     * @param response
     * @param dataGrid
     * @param modelMap
     * @return
     */
    @RequestMapping(value="/exportEXL",method=RequestMethod.GET)
    
    public String exportEXL(@RequestParam(name="roleId",required=false) Long roleId,
            HttpServletRequest request, HttpServletResponse response,
           ModelMap modelMap
            
           ) {
        
    
        try {
            String dateType = "yyyy";
            SimpleDateFormat df = new SimpleDateFormat(dateType);// 设置日期格式
            SimpleDateFormat df1 = new SimpleDateFormat("yyyy.MM.dd");// 设置日期格式
            // 创建HSSFWorkbook对象(excel的文档对象)
            HSSFWorkbook wb = new HSSFWorkbook();
            HSSFRow row = null;
            HSSFCell cell = null;
            // 建立新的sheet对象(excel的表单) 并设置sheet名字
            HSSFSheet sheet = wb.createSheet(df1.format(new Date())+"信息统计表");   
            sheet.setDefaultRowHeightInPoints(20);// 设置缺省列高            sheet.setDefaultColumnWidth(20);//设置缺省列宽
            //----------------标题样式---------------------
            HSSFCellStyle titleStyle3 = wb.createCellStyle();        //标题样式
            titleStyle3.setAlignment(HSSFCellStyle.ALIGN_CENTER);
            titleStyle3.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
            HSSFFont ztFont = wb.createFont();   
            ztFont.setItalic(false);                     // 设置字体为斜体字   
            ztFont.setColor(Font.COLOR_NORMAL);            // 将字体设置为“红色”   
            ztFont.setFontHeightInPoints((short)16);    // 将字体大小设置为18px   
            ztFont.setFontName("宋体");             // 将“宋体”字体应用到当前单元格上  
           // ztFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);    //加粗
//             ztFont.setUnderline(Font.U_DOUBLE);         // 添加(Font.U_SINGLE单条下划线/Font.U_DOUBLE双条下划线)   
//              ztFont.setStrikeout(true);                  // 是否添加删除线   
             titleStyle3.setFont(ztFont);
            //-------------------------------------------
             //----------------二级标题格样式----------------------------------
             HSSFCellStyle titleStyle2 = wb.createCellStyle();        //表格样式
             titleStyle2.setAlignment(HSSFCellStyle.ALIGN_CENTER);   //左右居中
             titleStyle2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//上下居中
             HSSFFont ztFont2 = wb.createFont();   
             ztFont2.setItalic(false);                     // 设置字体为斜体字   
             ztFont2.setColor(Font.COLOR_NORMAL);            // 将字体设置为“红色”   
             ztFont2.setFontHeightInPoints((short)22);    // 将字体大小设置为18px   
             ztFont2.setFontName("黑体");             // 字体应用到当前单元格上   
             ztFont2.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);    //加粗
//                 ztFont.setUnderline(Font.U_DOUBLE);         // 添加(Font.U_SINGLE单条下划线/Font.U_DOUBLE双条下划线)   
//                  ztFont.setStrikeout(true);                  // 是否添加删除线   
             titleStyle2.setFont(ztFont2);
             //--------------------------------------------------------------------
             //------------------------三级标题-----------
             HSSFCellStyle titleStyle4= wb.createCellStyle();        //标题样式
             titleStyle4.setAlignment(HSSFCellStyle.ALIGN_CENTER);
             titleStyle4.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//上下居中
             titleStyle4.setWrapText(true);//自动换行
             HSSFFont ztFont3 = wb.createFont();   
             ztFont3.setItalic(false);                     // 设置字体为斜体字   
             ztFont3.setColor(Font.COLOR_NORMAL);            // 将字体设置为“红色”   
             ztFont3.setFontHeightInPoints((short)16);    // 将字体大小设置为18px   
             ztFont3.setFontName("黑体");             // 将“宋体”字体应用到当前单元格上  
             ztFont3.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);    //加粗
//              ztFont.setUnderline(Font.U_DOUBLE);         // 添加(Font.U_SINGLE单条下划线/Font.U_DOUBLE双条下划线)   
//               ztFont.setStrikeout(true);                  // 是否添加删除线   
              titleStyle4.setFont(ztFont3);
            //----------------------------------------------------------
            //----------------单元格样式----------------------------------
              HSSFCellStyle cellStyle = wb.createCellStyle();        //表格样式
              cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
              cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
              cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下边框    
              cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框    
              cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框    
              cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框
              Font cellFont = wb.createFont();   
              cellFont.setItalic(false);                     // 设置字体为斜体字   
              cellFont.setColor(Font.COLOR_NORMAL);            // 将字体设置为“红色”   
              cellFont.setFontHeightInPoints((short)12);    // 将字体大小设置为18px   
              cellFont.setFontName("仿宋_GB2312");             // 字体应用到当前单元格上   
              //cellFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
              cellStyle.setFont(cellFont);
              cellStyle.setWrapText(true);//设置自动换行
            //----------------------------------------------------------
            // ----------------------创建第一行---------------
            // 在sheet里创建第一行,参数为行索引(excel的行),可以是0~65535之间的任何一个
            row = sheet.createRow(0);
            // 创建单元格(excel的单元格,参数为列索引,可以是0~255之间的任何一个
            cell = row.createCell(2);
            // 合并单元格CellRangeAddress构造参数依次表示起始行,截至行,起始列, 截至列
            sheet.addMergedRegion(new CellRangeAddress(0, 0, 2, 2));
            // 设置单元格内容
            cell.setCellValue("附件1");
            cell.setCellStyle(titleStyle3);
            // ----------------------------------------------
            // ----------------------创建第二行---------------
            // 在sheet里创建第一行,参数为行索引(excel的行),可以是0~65535之间的任何一个
            row = sheet.createRow(1);
            // 创建单元格(excel的单元格,参数为列索引,可以是0~255之间的任何一个
            cell = row.createCell(0);
            // 合并单元格CellRangeAddress构造参数依次表示起始行,截至行,起始列, 截至列
            sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, 19));
            // 设置单元格内容
            cell.setCellValue("信息统计表");
            cell.setCellStyle(titleStyle2);
            // ----------------------------------------------

            // ------------------创建第三行(单位、填表日期)---------------------
            row = sheet.createRow(2); // 创建第三行
            cell = row.createCell(1);
            cell.setCellValue("单位名称: ");
            cell.setCellStyle(titleStyle3);
            sheet.addMergedRegion(new CellRangeAddress(2, 2, 1, 3));
            
            cell.setCellStyle(titleStyle3);
            cell = row.createCell(4); // 填表时间
            sheet.addMergedRegion(new CellRangeAddress(2, 2, 4, 5));
            cell.setCellValue("学校(盖章)");
            cell.setCellStyle(titleStyle3);
            // ----------------------------------------------

            // ------------------创建表头start---------------------
           
            
            row = sheet.createRow(3); // 创建第四行
            row.setHeightInPoints(30); //设置行高
            cell = row.createCell(0);
            cell.setCellValue("序号");
            cell.setCellStyle(titleStyle4);
            sheet.autoSizeColumn(1, true);
            sheet.addMergedRegion(new CellRangeAddress(3, 4, 0, 0));
            
            
            sheet.addMergedRegion(new CellRangeAddress(3, 4, 1, 1));
            cell = row.createCell(1);
            cell.setCellValue("姓名");
            sheet.autoSizeColumn(1, true);
            cell.setCellStyle(titleStyle4);
            
            sheet.addMergedRegion(new CellRangeAddress(3, 4, 2, 2));
            cell = row.createCell(2);
            cell.setCellValue("性别");
            cell.setCellStyle(titleStyle4);
            
            sheet.addMergedRegion(new CellRangeAddress(3, 4, 3, 3));
            cell = row.createCell(3);
            sheet.setColumnWidth(3, 16* 256);  //设置列宽,20个字符宽
            cell.setCellValue("政治面貌");
            sheet.autoSizeColumn(1, true);
            cell.setCellStyle(titleStyle4);

            
            sheet.addMergedRegion(new CellRangeAddress(3, 4, 4, 4));
            sheet.setColumnWidth(4, 16 * 256);  //设置列宽,20个字符宽
            cell = row.createCell(4);
            cell.setCellValue("出生年份");
            sheet.autoSizeColumn(1, true);
            cell.setCellStyle(titleStyle4);
            
            sheet.addMergedRegion(new CellRangeAddress(3, 4, 5, 5));
            sheet.setColumnWidth(5, 16 * 256);  //设置列宽,20个字符宽
            cell = row.createCell(5);
            cell.setCellValue("出生月份");
            cell.setCellStyle(titleStyle4);
            
            sheet.addMergedRegion(new CellRangeAddress(3, 4, 6, 6));
            sheet.setColumnWidth(6, 16 * 256);  //设置列宽,20个字符宽
            cell = row.createCell(6);
            cell.setCellValue("出生日期");
            cell.setCellStyle(titleStyle4);
            
            
            sheet.addMergedRegion(new CellRangeAddress(3, 4, 7, 7));
            cell = row.createCell(7);
            sheet.setColumnWidth(7, 30* 256);  //设置列宽,20个字符宽
            cell.setCellValue("身份证号");
            cell.setCellStyle(titleStyle4);
            
            sheet.addMergedRegion(new CellRangeAddress(3, 4, 8, 8));
            cell = row.createCell(8);
            sheet.setColumnWidth(8, 15 * 256);  //设置列宽,20个字符宽
            cell.setCellValue("手机号");
            cell.setCellStyle(titleStyle4);
            
            sheet.addMergedRegion(new CellRangeAddress(3, 4, 9, 9));
            cell = row.createCell(9);
            sheet.setColumnWidth(9, 40 * 256);  //设置列宽,20个字符宽
            cell.setCellValue("学校");
            cell.setCellStyle(titleStyle4);
            
            sheet.addMergedRegion(new CellRangeAddress(3, 4, 10, 10));
            cell = row.createCell(10);
            sheet.setColumnWidth(10, 40 * 256);  //设置列宽,20个字符宽
            cell.setCellValue("院系");
            cell.setCellStyle(titleStyle4);
            
            sheet.addMergedRegion(new CellRangeAddress(3, 4, 11, 11));
            cell = row.createCell(11);
            sheet.setColumnWidth(11, 16 * 256);  //设置列宽,20个字符宽
            cell.setCellValue("时间");
            cell.setCellStyle(titleStyle4);
            
            sheet.addMergedRegion(new CellRangeAddress(3, 4, 12, 12));
            cell = row.createCell(12);
            sheet.setColumnWidth(12, 16* 256);  //设置列宽,20个字符宽
            cell.setCellValue("时间");
            cell.setCellStyle(titleStyle4);
            
            sheet.addMergedRegion(new CellRangeAddress(3, 4, 13, 13));
            cell = row.createCell(13);
            sheet.setColumnWidth(13, 16 * 256);  //设置列宽,20个字符宽
            cell.setCellValue("时长");
            cell.setCellStyle(titleStyle4);
            
            sheet.addMergedRegion(new CellRangeAddress(3, 3, 14, 16));
            cell = row.createCell(14);
            cell.setCellValue("数量");
            cell.setCellStyle(titleStyle4);
          
          
            
            sheet.addMergedRegion(new CellRangeAddress(3, 4, 17, 17));
            cell = row.createCell(17);
            sheet.setColumnWidth(17, 20 * 256);  //设置列宽,20个字符宽
            cell.setCellValue("职务");
            cell.setCellStyle(titleStyle4);
            
            sheet.addMergedRegion(new CellRangeAddress(3, 4, 18, 18));
            cell = row.createCell(18);
            sheet.setColumnWidth(18, 20 * 256);  //设置列宽,20个字符宽
            cell.setCellValue("职务");
            cell.setCellStyle(titleStyle4);
            
            sheet.addMergedRegion(new CellRangeAddress(3, 4, 19, 19));
            cell = row.createCell(19);
            sheet.setColumnWidth(19, 40 * 256);  //设置列宽,20个字符宽
            cell.setCellValue("职务");
            cell.setCellStyle(titleStyle4);
            
            sheet.addMergedRegion(new CellRangeAddress(3, 4, 20, 20));
            cell = row.createCell(20);
            sheet.setColumnWidth(20, 40 * 256);  //设置列宽,20个字符宽
            cell.setCellValue("职务");
            cell.setCellStyle(titleStyle4);
            
            sheet.addMergedRegion(new CellRangeAddress(3, 4, 21, 21));
            cell = row.createCell(21);
            sheet.setColumnWidth(21, 16 * 256);  //设置列宽,20个字符宽
            cell.setCellValue("学历");
            cell.setCellStyle(titleStyle4);
            
            sheet.addMergedRegion(new CellRangeAddress(3, 4, 22, 22));
            cell = row.createCell(22);
            sheet.setColumnWidth(22, 16 * 256);  //设置列宽,20个字符宽
            cell.setCellValue("学位");
            cell.setCellStyle(titleStyle4);
            
            sheet.addMergedRegion(new CellRangeAddress(3, 4, 23, 23));
            cell = row.createCell(23);
            sheet.setColumnWidth(23, 16 * 256);  //设置列宽,20个字符宽
            cell.setCellValue("方式");
            cell.setCellStyle(titleStyle4);
            
            sheet.addMergedRegion(new CellRangeAddress(3, 4, 24, 24));
            
            cell = row.createCell(24);
            cell.setCellValue("备注");
            cell.setCellStyle(titleStyle4);
         
            
            //--------------------------- 创建第五行--------------------
            row = sheet.createRow(4);
            
            cell = row.createCell(0);
            cell.setCellStyle(titleStyle4);
            
            cell = row.createCell(1);
            cell.setCellStyle(titleStyle4);
            
            cell = row.createCell(2);
            cell.setCellStyle(titleStyle4);
            
            cell = row.createCell(3);
            cell.setCellStyle(titleStyle4);
            
            cell = row.createCell(4);
            cell.setCellStyle(titleStyle4);
            
            cell = row.createCell(5);
            cell.setCellStyle(titleStyle4);
            
            cell = row.createCell(6);
            cell.setCellStyle(titleStyle4);
            
            cell = row.createCell(7);
            cell.setCellStyle(titleStyle4);
            
            cell = row.createCell(8);
            cell.setCellStyle(titleStyle4);
            
            
            
            cell = row.createCell(9);
            cell.setCellStyle(titleStyle4);
            
            cell = row.createCell(10);
            cell.setCellStyle(titleStyle4);
            
            cell = row.createCell(11);
            cell.setCellStyle(titleStyle4);
            
            cell = row.createCell(12);
            cell.setCellStyle(titleStyle4);
            
            cell = row.createCell(13);
            cell.setCellStyle(titleStyle4);
            
            cell = row.createCell(14);
            cell.setCellStyle(titleStyle4);
            
            
        
            
            sheet.addMergedRegion(new CellRangeAddress(4, 4, 14, 14));
            cell = row.createCell(14);
            sheet.setColumnWidth(14, 16 * 256);  //设置列宽,20个字符宽
            cell.setCellValue("生");
            cell.setCellStyle(titleStyle4);
            
           
            sheet.addMergedRegion(new CellRangeAddress(4, 4, 15, 15));
            cell = row.createCell(15);
            sheet.setColumnWidth(15, 16 * 256);  //设置列宽,20个字符宽
            cell.setCellValue("生");
            cell.setCellStyle(titleStyle4);
            
//            cell = row.createCell(1);
//            cell.setCellStyle(titleStyle4);
            
            sheet.addMergedRegion(new CellRangeAddress(4, 4, 16, 16));
            cell = row.createCell(16);
            sheet.setColumnWidth(16, 16 * 256);  //设置列宽,20个字符宽
            cell.setCellValue("生");
            cell.setCellStyle(titleStyle4);
            
          
            cell = row.createCell(17);
            cell.setCellStyle(titleStyle4);

            cell = row.createCell(18);
            cell.setCellStyle(titleStyle4);
            cell = row.createCell(19);
            cell.setCellStyle(titleStyle4);
            
            cell = row.createCell(20);
            cell.setCellStyle(titleStyle4);
            cell = row.createCell(21);
            cell.setCellStyle(titleStyle4);
            
            cell = row.createCell(22);
            cell.setCellStyle(titleStyle4);
            cell = row.createCell(23);
            cell.setCellStyle(titleStyle4);
            cell = row.createCell(24);
            cell.setCellStyle(titleStyle4);
            //-------------------------表头end---------------------
            
            
           /**
            *
            * 查询数据代码需要更改填写
            *
            *
            */
//


/**
这里是需要查询所需要的数据放到bean中以方便导出使用
这里的代码我删掉了,就是查询数据,总到一个bean里面
*/


//


        for(int i=0;i<daochu.size();i++){
             List<Object> data = new ArrayList<Object>();
             daoChubean  chubean=new daoChubean();
             chubean=daochu.get(i);
             data.add(i+1);
             data.add(chubean.getName());
            
        
             int rowNum = 5+i;    //从第四行开始
             row = sheet.createRow(rowNum);
             for (int j = 0; j < data.size(); j++) {        //将数据添加到单元格中    
//                         System.out.println(data.get(j));
                 sheet.addMergedRegion(new CellRangeAddress(rowNum, rowNum, j, j));
                 cell = row.createCell(j);
                 cell.setCellValue(""+data.get(j)+"");
                 cell.setCellStyle(cellStyle);
             }
        }
       
        
       
        
        
    
        // 输出Excel文件
        OutputStream output = response.getOutputStream();
        response.reset();
        String fileName="信息统计表";     //用这个可以在前端页面上自主选择下载地址到本地的硬盘,
        response.setHeader("Content-Disposition","attachment;filename=" + new String( fileName.getBytes("gb2312"), "ISO8859-1" ) );    //filename =  文件名
        response.setContentType("application/msexcel");
        wb.write(output);
        output.close();
           
            
            
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
        
    }
    
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值