使用poi實現動態合併單元格導出excel

使用poi進行動態合併單元格,

參考博客:https://blog.csdn.net/yuan890720/article/details/52368366

根據賣家公司字段匹配導出結果樣式:

在這裏插入圖片描述

代碼如下

package test;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCell;

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

/**

  • Created by LH on 2019/8/20 9:57
    */
    public class Test2 {

    // 日誌
    private static Logger log = Logger.getLogger(Test2.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 info) {

      /**

      • 新增列:買家公司交易金額
      • 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.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.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;//所要合併單元格的地址值
CellRangeAddress region0;//所要合併單元格的地址值
CellRangeAddress region1;//所要合併單元格的地址值
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());//最後一行的數據
                     region0=new CellRangeAddress(i-m+1, i+1, 0, 0);//h合併單元格
                     region1=new CellRangeAddress(i-m+1, i+1, 1, 1);//h合併單元格
                    region=new CellRangeAddress(i-m+1, i+1, 6, 6);//h合併單元格
                    sheet.addMergedRegion(region);
                    sheet.addMergedRegion(region0);
                    sheet.addMergedRegion(region1);
                    //取得合併的單元格並把數據插入
                    sheet.getRow(i-m+1).getCell(6).setCellValue(a+b+c);
                    sheet.getRow(i-m+1).getCell(0).setCellValue(info.get(i-m).getOutOrderNo());
                    sheet.getRow(i-m+1).getCell(1).setCellValue(info.get(i-m).getTitle());
                }else{
                    //判斷上一行和上兩行的值是否相同,如果相同就就將上他們合併,並插入值
                    if(i>1&&info.get(i-2).getBuyCompany().equals(info.get(i-1).getBuyCompany())){
                        Double b=Double.parseDouble(info.get(i-m).getPay());
                        region0=new CellRangeAddress(i-m+1, i, 0, 0);
                        region1=new CellRangeAddress(i-m+1, i, 1, 1);
                        region=new CellRangeAddress(i-m+1, i, 6, 6);
                        sheet.addMergedRegion(region);
                        sheet.addMergedRegion(region0);
                        sheet.addMergedRegion(region1);
                        sheet.getRow(i-m+1).getCell(6).setCellValue(a+b);
                        sheet.getRow(i-m+1).getCell(0).setCellValue(info.get(i-m).getOutOrderNo());
                        sheet.getRow(i-m+1).getCell(1).setCellValue(info.get(i-m).getTitle());

                        cell0List.setCellValue(info.get(i).getOutOrderNo());
                        cell1List.setCellValue(info.get(i).getTitle());
                        cell6List.setCellValue(Double.parseDouble(info.get(i).getPay()));
                        m=1;
                        a=0.0;
                    }else{
                        //如果不相同就直接填入值

                        cell6List.setCellValue(Double.parseDouble(info.get(i).getPay()));
                        cell0List.setCellValue( info.get(i).getOutOrderNo());
                        cell1List.setCellValue( info.get(i).getTitle());
                        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 Test2() {
}





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");
        order.setNumber(10);
        info.add(order);

    }
    for (int i = 0; i < 5; i++) {
        OrderInfoBean order1 = new OrderInfoBean();
        order1.setOutOrderNo("123456123");
        order1.setTitle("塑料");
        order1.setPay("1000.120");
        order1.setTransfer("10.010");
        order1.setSaller("zhangsan");
        order1.setSalCompany("張三的公司111111");
        order1.setBuyer("李四");
        order1.setBuyCompany("李四的公司111111");
        order1.setAddress("beijing");
        order1.setContact1("13110011002");
        order1.setContact2("15610011002");
        order1.setDeliveryPeople("王五");
        order1.setDeliveryPhone("12345698710");
        order1.setDeliveryCar("京A00001");
        order1.setDeliveryTime("2016-8-18");
        order1.setNumber(5);
        info.add(order1);
    }

    OrderInfoBean order1 = new OrderInfoBean();
    order1.setOutOrderNo("123456123");
    order1.setTitle("塑料");
    order1.setPay("1000.120");
    order1.setTransfer("10.010");
    order1.setSaller("zhangsan");
    order1.setSalCompany("張三的公司1111111111122");
    order1.setBuyer("李四");
    order1.setBuyCompany("李四的公司1111111111122");
    order1.setAddress("beijing");
    order1.setContact1("13110011002");
    order1.setContact2("15610011002");
    order1.setDeliveryPeople("王五");
    order1.setDeliveryPhone("12345698710");
    order1.setDeliveryCar("京A00001");
    order1.setDeliveryTime("2016-8-18");
    order1.setNumber(5);
    info.add(order1);

    Test2.createExcelFile("D:\\test111.xls", info);
    System.out.println("OK!");
}

static class OrderInfoBean {
    private String outOrderNo;
    private String title;
    private String pay;
    private String transfer;
    private String saller;
    private String salCompany;
    private String buyer;
    private String buyCompany;
    private String address;
    private String contact1;
    private String contact2;
    private String deliveryPeople;
    private String deliveryPhone;
    private String deliveryCar;
    private String deliveryTime;
    private String deliveryMethod;
    private Integer number;

    public String getOutOrderNo() {
        return outOrderNo;
    }

    public void setOutOrderNo(String outOrderNo) {
        this.outOrderNo = outOrderNo;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getPay() {
        return pay;
    }

    public void setPay(String pay) {
        this.pay = pay;
    }

    public String getTransfer() {
        return transfer;
    }

    public void setTransfer(String transfer) {
        this.transfer = transfer;
    }

    public String getSaller() {
        return saller;
    }

    public void setSaller(String saller) {
        this.saller = saller;
    }

    public String getSalCompany() {
        return salCompany;
    }

    public void setSalCompany(String salCompany) {
        this.salCompany = salCompany;
    }

    public String getBuyer() {
        return buyer;
    }

    public void setBuyer(String buyer) {
        this.buyer = buyer;
    }

    public String getBuyCompany() {
        return buyCompany;
    }

    public void setBuyCompany(String buyCompany) {
        this.buyCompany = buyCompany;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getContact1() {
        return contact1;
    }

    public void setContact1(String contact1) {
        this.contact1 = contact1;
    }

    public String getContact2() {
        return contact2;
    }

    public void setContact2(String contact2) {
        this.contact2 = contact2;
    }

    public String getDeliveryPeople() {
        return deliveryPeople;
    }

    public void setDeliveryPeople(String deliveryPeople) {
        this.deliveryPeople = deliveryPeople;
    }

    public String getDeliveryPhone() {
        return deliveryPhone;
    }

    public void setDeliveryPhone(String deliveryPhone) {
        this.deliveryPhone = deliveryPhone;
    }

    public String getDeliveryMethod() {
        return deliveryMethod;
    }

    public void setDeliveryMethod(String deliveryMethod) {
        this.deliveryMethod = deliveryMethod;
    }

    public String getDeliveryCar() {
        return deliveryCar;
    }

    public void setDeliveryCar(String deliveryCar) {
        this.deliveryCar = deliveryCar;
    }

    public String getDeliveryTime() {
        return deliveryTime;
    }

    public void setDeliveryTime(String deliveryTime) {
        this.deliveryTime = deliveryTime;
    }

    public Integer getNumber() {
        return number;
    }

    public void setNumber(Integer number) {
        this.number = number;
    }
}

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章