Java动态生成excel表格,动态合并多个单元格

//用HSSF动态生成表格,已经合并的表格不能进行再次合并,所以我的思路是,做一个计数器,做一个数据总和统计

//当本行数据和上一行数据不相同时,将上次的相同的单元格合并并注入数据


package com.sound.utils;


import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
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.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCell;

import com.sound.ezaisheng.bin.OrderInfoBean;

/**
 * 操作表格
 *
 * @author zhangxiantao
 *
 *         2016年8月18日
 */
public class OperateExcelByPoi {

    // 日志
    private static Logger log = Logger.getLogger(OperateExcelByPoi.class
            .getName());

    /**
     * 判断文件是否存在
     *
     * @param path
     * @return
     */
    public static boolean checkFile(String path) {
        File file = new File(path);
        if (file.exists()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 建立订单查询ExcelFile
     *
     * @param excelPath
     * @return
     */
    public static boolean createExcelFile(String excelPath,List<OrderInfoBean> info) {
 
        /**
         * 新增列:买家公司交易金额
         * 2016.8.29
         * NorthLee
         *
         */
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("实际成交订单");
        
        HSSFCellStyle style = workbook.createCellStyle();
        HSSFFont font = workbook.createFont();
        font.setFontHeightInPoints((short) 12);//字号
        font.setFontName("宋体");
        font.setBold(true); //粗体
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//垂直
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);//水平
        style.setFont(font);
        style.setWrapText(true);
        
        // 标题行
        HSSFRow row = sheet.createRow(0);
        // 行高
        row.setHeight((short) (20*20));
        // 列数
        HSSFCell cell0 = row.createCell(0);
        cell0.setCellStyle(style);
        cell0.setCellValue("订单号");
        
        HSSFCell cell1 = row.createCell(1);
        cell1.setCellStyle(style);
        cell1.setCellValue("货物标题");
        
        HSSFCell cell2 = row.createCell(2);
        cell2.setCellStyle(style);
        cell2.setCellValue("支付价格");
        
        HSSFCell cell3 = row.createCell(3);
        cell3.setCellStyle(style);
        cell3.setCellValue("批付价格");
        
        HSSFCell cell4 = row.createCell(4);
        cell4.setCellStyle(style);
        cell4.setCellValue("卖家真实姓名");
        
        HSSFCell cell5 = row.createCell(5);
        cell5.setCellStyle(style);
        cell5.setCellValue("卖家公司");

        
        HSSFCell cell6 = row.createCell(6);
        cell6.setCellStyle(style);
        cell6.setCellValue("买家公司交易总额");
        
        HSSFCell cell7 = row.createCell(7);
        cell7.setCellStyle(style);
        cell7.setCellValue("买家真实姓名");
        
        HSSFCell cell8 = row.createCell(8);
        cell8.setCellStyle(style);
        cell8.setCellValue("买家公司");
        
        HSSFCell cell9 = row.createCell(9);
        cell9.setCellStyle(style);
        cell9.setCellValue("货运地址");
        
        HSSFCell cell10 = row.createCell(10);
        cell10.setCellStyle(style);
        cell10.setCellValue("买家联系方式1");
        
        HSSFCell cell11 = row.createCell(11);
        cell11.setCellStyle(style);
        cell11.setCellValue("买家联系方式2");
        
        HSSFCell cell12 = row.createCell(12);
        cell12.setCellStyle(style);
        cell12.setCellValue("货运方式");
        
        HSSFCell cell13 = row.createCell(13);
        cell13.setCellStyle(style);
        cell13.setCellValue("货运联系人");
        
        HSSFCell cell14 = row.createCell(14);
        cell14.setCellStyle(style);
        cell14.setCellValue("货运车牌号");
        
        HSSFCell cell15 = row.createCell(15);
        cell15.setCellStyle(style);
        cell15.setCellValue("货运联系方式");
        
        HSSFCell cell16 = row.createCell(16);
        cell16.setCellStyle(style);
        cell16.setCellValue("发货时间");
        
        // 内容行
        if(info != null && info.size() > 0){
            HSSFCellStyle styleList = workbook.createCellStyle();
            HSSFFont fontList = workbook.createFont();
            fontList.setFontHeightInPoints((short) 12);//字号
            fontList.setFontName("宋体");
            font.setBold(false);//粗体
            styleList.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//垂直
            styleList.setAlignment(HSSFCellStyle.ALIGN_CENTER);//水平
            styleList.setFont(font);
            
            /**
             * m,a在插入买家公司交易总额的数据的时候用
             *    m是统计同一个公司出现相同的次数
             *     a是相同公司出现的交易额的累加
             */
            
            int m=1;
            Double a=0.0;//不包括合并单元格的第一行的数据
            for (int i = 0; i < info.size(); i++) {
                HSSFRow rowList = sheet.createRow(i+1);
                // 行高
                rowList.setHeight((short) (20*20));
                // 列数
                HSSFCell cell0List = rowList.createCell(0);
                cell0List.setCellStyle(styleList);
                cell0List.setCellValue(info.get(i).getOutOrderNo());
                
                HSSFCell cell1List = rowList.createCell(1);
                cell1List.setCellStyle(styleList);
                cell1List.setCellValue(info.get(i).getTitle());
                
                HSSFCell cell2List = rowList.createCell(2);
                cell2List.setCellStyle(styleList);
                cell2List.setCellValue(Double.parseDouble(info.get(i).getPay()));
                
                HSSFCell cell3List = rowList.createCell(3);
                cell3List.setCellStyle(styleList);
                cell3List.setCellValue(Double.parseDouble(info.get(i).getTransfer()));
                
                HSSFCell cell4List = rowList.createCell(4);
                cell4List.setCellStyle(styleList);
                cell4List.setCellValue(info.get(i).getSaller());
                
                HSSFCell cell5List = rowList.createCell(5);
                cell5List.setCellStyle(styleList);
                cell5List.setCellValue(info.get(i).getSalCompany());
                
//                 插入新增列数据
//                说明:由于已经合并的单元格不能进行再次合并,所以先进行判断和数据统计最后进行单元格的合并                
                HSSFCell cell6List = rowList.createCell(6);
                cell6List.setCellStyle(styleList);
                CellRangeAddress region;//所要合并单元格的地址值
                if(i==0){
                    cell6List.setCellValue(Double.parseDouble(info.get(0).getPay()));
                
                }else{
                        // 判断本行是否是最后一行  并且 本行的公司名是否和上个公司相同,如果相同取得支付的值,并累加
                        if((i!=info.size()-1)&&(info.get(i).getBuyCompany().equals(info.get(i-1).getBuyCompany()))){
                            a += Double.parseDouble(info.get(i).getPay());
                            m++;
                            // 判断本行是否是最后一行  并且 本行的公司名是否和上个公司相同,如果相同取得支付的值,并累加,再合并单元格并插入数据
                        }else if((i==info.size()-1)&&(info.get(i).getBuyCompany().equals(info.get(i-1).getBuyCompany()))){
                            
                            Double b=Double.parseDouble(info.get(i-m).getPay());//所合并单元格的第一行数据
                            Double c=Double.parseDouble(info.get(i).getPay());//最后一行的数据
                            region=new CellRangeAddress(i-m+1, i+1, 6, 6);//h合并单元格
                            sheet.addMergedRegion(region);
                            //取得合并的单元格并把数据插入
                            sheet.getRow(i-m+1).getCell(6).setCellValue(a+b+c);
                        }else{
                        //判断上一行和上两行的值是否相同,如果相同就就将上他们合并,并插入值
                            if(i>1&&info.get(i-2).getBuyCompany().equals(info.get(i-1).getBuyCompany())){
                                Double b=Double.parseDouble(info.get(i-m).getPay());
                                region=new CellRangeAddress(i-m+1, i, 6, 6);
                                sheet.addMergedRegion(region);
                                sheet.getRow(i-m+1).getCell(6).setCellValue(a+b);
                                
                                cell6List.setCellValue(Double.parseDouble(info.get(i).getPay()));
                                m=1;
                                a=0.0;
                            }else{
                                //如果不相同就直接填入值
                                
                                cell6List.setCellValue(Double.parseDouble(info.get(i).getPay()));
                                m=1;
                            }
                        }
                }
                        
                HSSFCell cell7List = rowList.createCell(7);
                cell7List.setCellStyle(styleList);
                cell7List.setCellValue(info.get(i).getBuyer());
                
                HSSFCell cell8List = rowList.createCell(8);
                cell8List.setCellStyle(styleList);
                cell8List.setCellValue(info.get(i).getBuyCompany());
                
                HSSFCell cell9List = rowList.createCell(9);
                cell9List.setCellStyle(styleList);
                cell9List.setCellValue(info.get(i).getAddress());
                
                HSSFCell cell10List = rowList.createCell(10);
                cell10List.setCellStyle(styleList);
                cell10List.setCellValue(info.get(i).getContact1());
                
                HSSFCell cell11List = rowList.createCell(11);
                cell11List.setCellStyle(styleList);
                cell11List.setCellValue(info.get(i).getContact2());
                
                HSSFCell cell12List = rowList.createCell(12);
                cell12List.setCellStyle(styleList);
                cell12List.setCellValue(info.get(i).getDeliveryMethod());
                
                HSSFCell cell13List = rowList.createCell(13);
                cell13List.setCellStyle(styleList);
                cell13List.setCellValue(info.get(i).getDeliveryPeople());
                
                HSSFCell cell14List = rowList.createCell(14);
                cell14List.setCellStyle(styleList);
                cell14List.setCellValue(info.get(i).getDeliveryCar());
                
                HSSFCell cell15List = rowList.createCell(15);
                cell15List.setCellStyle(styleList);
                cell15List.setCellValue(info.get(i).getDeliveryPhone());
                
                HSSFCell cell16List = rowList.createCell(16);
                cell16List.setCellStyle(styleList);
                cell16List.setCellValue(info.get(i).getDeliveryTime());
            }
            HSSFRow rowSum = sheet.createRow(info.size()+1);
            HSSFCell cellSum = rowSum.createCell(2);
            cellSum.setCellType(XSSFCell.CELL_TYPE_FORMULA);
            cellSum.setCellFormula("SUM(C2:C"+(info.size()+1)+")" );
        }
        // 列宽
   
  
        sheet.setColumnWidth(0, 15*280);
        sheet.setColumnWidth(1, 40*280);
        sheet.setColumnWidth(2, 15*280);
        sheet.setColumnWidth(3, 15*280);
        sheet.setColumnWidth(4, 15*280);
        sheet.setColumnWidth(5, 50*280);
        sheet.setColumnWidth(6, 25*280);
        sheet.setColumnWidth(7, 15*280);
        sheet.setColumnWidth(8, 50*280);
        sheet.setColumnWidth(9, 50*280);
        sheet.setColumnWidth(10, 15*280);
        sheet.setColumnWidth(11, 15*280);
        sheet.setColumnWidth(12, 15*280);
        sheet.setColumnWidth(13, 15*280);
        sheet.setColumnWidth(14, 15*280);
        sheet.setColumnWidth(15, 15*280);
        sheet.setColumnWidth(16, 15*280);
        
        return outputHSSFWorkbook(workbook, excelPath);
    }

    /**
     * 创建Excel文件
     *
     * @param wb
     * @param excelPath
     * @return
     */
    private static boolean outputHSSFWorkbook(HSSFWorkbook wb, String excelPath) {
        int index = excelPath.lastIndexOf(File.separator);
        String path = excelPath.substring(0, index);
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        FileOutputStream fOut = null;
        try {
            fOut = new FileOutputStream(excelPath);
            wb.write(fOut);
            fOut.flush();
            log.info("文件正在生成......");
            return true;
        } catch (FileNotFoundException e) {
            log.error("未找到要写的文件");
        } catch (IOException e) {
            log.error("写文件是IO异常");
        } finally {
            try {
                if (fOut != null)
                    fOut.close();
            } catch (Exception e) {
                log.error("关闭文件流错误");
            }
        }
        return false;
    }

    private OperateExcelByPoi() {
    }

    public static void main(String[] args) {
        List<OrderInfoBean> info = new ArrayList<OrderInfoBean>();
        for (int i = 0; i < 10; i++) {
            OrderInfoBean order = new OrderInfoBean();
            order.setOutOrderNo("123456");
            order.setTitle("塑料");
            order.setPay("1000.120");
            order.setTransfer("10.010");
            order.setSaller("zhangsan");
            order.setSalCompany("张三的公司");
            order.setBuyer("李四");
            order.setBuyCompany("李四的公司");
            order.setAddress("beijing");
            order.setContact1("13110011002");
            order.setContact2("15610011002");
            order.setDeliveryPeople("王五");
            order.setDeliveryPhone("12345698710");
            order.setDeliveryCar("京A00001");
            order.setDeliveryTime("2016-8-18");
            info.add(order);
        }
        OperateExcelByPoi.createExcelFile("D:\\test.xls", info);
        System.out.println("OK!");
    }
}

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值