java 通用的導出 excel 合並單元格格式(二)


表格效果圖

思路 :

 1 excel 標題頭    這里的標題寫成了固定 

      標題的第一列  需要合並的單元格 需要填充

String[] head0 = new String[] { "登錄名", "是否使用", "單位名稱", "機要員", "聯系方式", "管轄區局",
"級別", "作業人員情況", "作業人員情況", "作業人員情況", "作業人員情況", "作業人員情況",
"系統數據總數", "維保電梯(台)","設備數","設備數",
"分配情況(台)","分配情況(台)","單位地址" }; //在excel中的第2行每列的參數

     標題的第二列 

/* 在excel中的第3行每列(合並列)的參數 這里需要注意的是 從第幾列合並的時候 需要把前面不需要合並行的列 用"" 補上
(下表是從第7列 開始合並的行的 所以前面補了 6個"", 中間 兼職和總數之間 有一列是不需要合並行的 也補了一個"") */

 String[] head1 = new String[] { " ", " ", " ", " ", " ", " ","總數", "確定", "庫內", "庫外", "兼職", "","總數", "認保", "認脫","分配", "未分配"};

 2 excel 內容      通用方法寫入從后台數據庫查詢到的數據到 excel  

后台業務邏輯(控制器 從后台數據庫查詢數據)

@RequestMapping(value = "exportMntOrgData")
    public void exportMntOrgData(HttpServletRequest request, HttpServletResponse response){
        Map<String, Object> map = new HashMap<String, Object>();
        Principal principal = UserUtils.getPrincipal();
         getManagerOrgId(map); // 判斷當前登錄賬號是否是市局的id 如果是 supOrgId置為空  查詢所有 
        // 2、導出
        String filename = "管理區局("+principal.getOrgname()+") 維保單位列表 .xls";
        List<Map<String, Object>> list = (List<Map<String, Object>>) mntOrgListStatisticsService.exportMntOrgList(map);
        //String path="exportTitle/mntWorker.xml";
           String[] head0 = new String[] { "登錄名", "是否使用", "單位名稱", "機要員", "聯系方式", "管轄區局",
                   "級別", "作業人員情況", "作業人員情況", "作業人員情況", "作業人員情況", "作業人員情況",
                   "系統數據", "設備數","設備數","設備數",
                   "分配情況(台)","分配情況(台)","單位地址" };//在excel中的第2行每列的參數
           /* 在excel中的第3行每列(合並列)的參數  這里需要注意的是   從第幾列合並的時候  需要把前面不需要合並行的列 用"" 補上
           (下表是從第7列 開始合並的行的  所以前面補了 6個"", 中間 兼職和總數之間 有一列是不需要合並行的    也補了一個"") */
           String[] head1 = new String[] { " ", " ", " ", " ", " ", " ","總數", "確定", "庫內", "庫外", "兼職", "","總數", "認保", "認脫","分配", "未分配"};
           String[] headnum0 = new String[] { "1,2,0,0", "1,2,1,1","1,2,2,2","1,2,3,3", "1,2,4,4","1,2,5,5","1,2,6,6", 
                   "1,1,7,11" , "1,2,12,12", "1,1,13,15", "1,1,16,17","1,2,18,18"};//對應excel中的行和列,下表從0開始{"開始行,結束行,開始列,結束列"}
           String[] headnum1 = new String[] { "2,2,7,7", "2,2,8,8", "2,2,9,9","2,2,10,10","2,2,11,11",
                                                 "2,2,13,13","2,2,14,14","2,2,15,15",
                                              "2,2,16,16","2,2,17,17"};
           String[] colName = new String[] { "username","username", 
                   "mntOrgName", "name", "mobile", "manageOrgName", "grade" ,"userTotal", 
                   "userTotal" , "userTotal1", "userTotal2", "userTotal3", 
                   "equTotal" , "equTotal", "mntEquCount", "notMntEquCount", 
                   "assignedEquCount" , "norAssignedEquCount", "address"};//需要顯示在excel中的參數對應的值,因為是用map存的,放的都是對應的key
           try {
               ExcelUtil.reportMergeXls(request, response, list, filename, head0,
                       headnum0, head1, headnum1, colName);//utils類需要用到的參數
           } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    }

從后台查詢 List<Map<String, Object>>  得到2條 的json 格式數據如下:

[ {username=鄧潤軍,username=44022519790424561X,mntOrgName=........}, 

   {username=鄧潤軍,username=44022519790424561X,mntOrgName=........}] 

 

通用的方法寫在 ExcelUtil里面

package com.nskj.utils;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Map.Entry;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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.slf4j.Logger;
import org.slf4j.LoggerFactory;


/***
 * excel 導出工具類
 * @author Administrator
 *
 */
public class ExcelUtil {
    private static DecimalFormat df = new DecimalFormat("0");
    // 默認單元格格式化日期字符串 
    private static SimpleDateFormat sdf = new SimpleDateFormat(  "yyyy-MM-dd HH:mm:ss"); 
    // 格式化數字
    private static DecimalFormat nf = new DecimalFormat("0.00");  
    
    private final static Logger logger = LoggerFactory.getLogger(ExcelUtil.class);
    
    /***
     * 讀取本地文件txt 獲取excel標題
     * @param path
     * @return
     */
    public static String getTitle(String path){
          FileInputStream fis = null;  
          InputStreamReader isr = null;  
          BufferedReader br = null; //用於包裝InputStreamReader,提高處理性能。因為BufferedReader有緩沖的,而InputStreamReader沒有。  
          String str = "";  
          String str1 = "";  
          try {
               fis = new FileInputStream(path);// FileInputStream  
               // 從文件系統中的某個文件中獲取字節  
               isr = new InputStreamReader(fis,"UTF-8");// InputStreamReader 是字節流通向字符流的橋梁,  
                //br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("")), "UTF-8"));
                br = new BufferedReader(isr);// 從字符輸入流中讀取文件中的內容,封裝了一個new InputStreamReader的對象  
               while ((str = br.readLine()) != null) {  
                str1 += str + ",";  
               } 
               str1 = str1.substring(0,str1.length()-1);
               // 當讀取的一行不為空時,把讀到的str的值賦給str1  
               System.out.println(str1);// 打印出str1  
              } catch (FileNotFoundException e) {  
               System.out.println("找不到指定文件");  
              } catch (IOException e) {  
               System.out.println("讀取文件失敗");  
              } finally {  
               try {  
                 br.close();  
                 isr.close();  
                 fis.close();  
                // 關閉的時候最好按照先后順序關閉最后開的先關閉所以先關s,再關n,最后關m  
               } catch (IOException e) {  
                e.printStackTrace();  
               }  
              } 
        return str1; //讀取excel表頭
    } 
    
    /***
     *  讀取服務器文件txt 獲取excel標題
     * @param fileName
     * @return
     */
    public  String getFile(String fileName) { 
        StringBuilder result = new StringBuilder("");
        String str1="";
        if(fileName.endsWith(".txt")){
        ClassLoader classLoader = getClass().getClassLoader();   
        File file = new File(classLoader.getResource(fileName).getFile());  
       
        try (Scanner scanner = new Scanner(file)) { 
            while (scanner.hasNextLine()) {  
                String line = scanner.nextLine();  
                result.append(line).append(",");  
            } 
            scanner.close();  
            str1=result.toString();
            str1 = str1.substring(0,str1.length()-1);
        } catch (IOException e) {  
            e.printStackTrace();  
        } 
        }
        if(fileName.endsWith(".xml")){
            FileInputStream fis = null;  
              InputStreamReader isr = null;  
              BufferedReader br = null; //用於包裝InputStreamReader,提高處理性能。因為BufferedReader有緩沖的,而InputStreamReader沒有。  
              String str = "";
              String str2="";
              try{
                fis = new FileInputStream(this.getClass().getClassLoader().getResource("/").getPath()+"/"+fileName);
                 isr = new InputStreamReader(fis,"UTF-8");// InputStreamReader 是字節流通向字符流的橋梁,  
                    //br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("")), "UTF-8"));
                    br = new BufferedReader(isr);// 從字符輸入流中讀取文件中的內容,封裝了一個new InputStreamReader的對象  
                   while ((str = br.readLine()) != null) {  
                       str2 += str + ",";  
                   } 
                  // str1 = str1.substring(0,str1.length()-1);
                  // str1 =str1.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>,", "");
                 // int str3=str2.indexOf(",");
                 // str1 = str2.substring(str3+1,str2.length() -(str3+1));
                  str1=str2.substring(str2.indexOf(',')+1).trim();
                  str1 = str1.substring(0,str1.length()-1);
              }    catch (IOException e) {  
                    e.printStackTrace();  
               } 
        }
        
        return str1;  
       
      } 
    
    
    //2. writeIntoExcel()  將datatable 數據寫入excel
    /*public static void writeExcel(ArrayList<ArrayList<Object>> result,String path){
        if(result == null){
            return;
        }
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet("sheet1");
        for(int i = 0 ;i < result.size() ; i++){
             HSSFRow row = sheet.createRow(i);
            if(result.get(i) != null){
                for(int j = 0; j < result.get(i).size() ; j ++){
                    HSSFCell cell = row.createCell(j);
                    cell.setCellValue(result.get(i).get(j).toString());
                }
            }
        }
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try
        {
            wb.write(os);
        } catch (IOException e){
            e.printStackTrace();
        }
        byte[] content = os.toByteArray();
        File file = new File(path);//Excel文件生成后存儲的位置。
        OutputStream fos  = null;
        try
        {
            fos = new FileOutputStream(file);
            fos.write(content);
            os.close();
            fos.close();
        }catch (Exception e){
            e.printStackTrace();
        }           
    }*/
    
    public static void export(List<Map<String, Object>> list, String filename, HttpServletResponse response, String titles) {
        try {
            response.setContentType("application/x-execl");
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + new String(filename.getBytes(), "ISO-8859-1"));
            ServletOutputStream outputStream = response.getOutputStream();
            
            exportExcel(list, filename, outputStream, titles);
            if (outputStream != null) {
                outputStream.close();
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    /**
     * 數據導出公用方法
     * 
     */
    public static void exportExcel(List<Map<String, Object>> list, String filename, ServletOutputStream outputStream,String titles) {
        try {
            Map<String, Object> map1 = list.get(0);
            StringBuilder sb = new StringBuilder();
            String[] fields=titles.split(",");
            /*sb.append(title);
            String[] fields = sb.toString().split(",");*/
            // 1、創建工作簿
            HSSFWorkbook workbook = new HSSFWorkbook();
            // 1.1、創建合並單元格對象
            CellRangeAddress cellRangeAddress = new CellRangeAddress(0, 0, 0, fields.length - 1);// 起始行號,結束行號,起始列號,結束列號
            CellRangeAddress cellRangeAddress1 = new CellRangeAddress(1, 1, 0, fields.length - 1);// 起始行號,結束行號,起始列號,結束列號
            CellRangeAddress cellRangeAddress2 = new CellRangeAddress(1, 1, 7, 12);// 起始行號,結束行號,起始列號,結束列號
            // 1.2、頭標題樣式
            HSSFCellStyle style1 = createCellStyle(workbook, (short) 18);
            // 1.3、列標題樣式
            HSSFCellStyle style2 = createCellStyle(workbook, (short) 13);
            String headRow = filename;
            // 2、創建工作表
            HSSFSheet sheet = workbook.createSheet(headRow);
            // 2.1、加載合並單元格對象
            sheet.addMergedRegion(cellRangeAddress);
            sheet.addMergedRegion(cellRangeAddress1);
            sheet.addMergedRegion(cellRangeAddress2);
            // sheet.addMergedRegion(cellRangeAddress4);
            // 設置默認列寬
            sheet.setDefaultColumnWidth(22);
            sheet.setDefaultRowHeightInPoints(22);
            sheet.autoSizeColumn(1, true);
            //
            // 3、創建行
            // 3.1、創建頭標題行;並且設置頭標題
            HSSFRow row1 = sheet.createRow(0);
            row1.setHeightInPoints(50);
            HSSFCell cell1 = row1.createCell(0);
            // 加載單元格樣式
            cell1.setCellStyle(style1);
            cell1.setCellValue(headRow);
            // 3.1、創建副標題行;並且設置
            HSSFRow row2 = sheet.createRow(1);
            row2.setHeightInPoints(25);
            HSSFCell cell2 = row2.createCell(0);
            // 3.2、創建列標題行;並且設置列標題
            HSSFRow row3 = sheet.createRow(2);
            
            /*String[] titles = new String[fields.length];
            for (int i = 0; i < fields.length; i++) {
                titles[i] = getTitles(type, fields[i]);
            }*/
            
            for (int i = 0; i < fields.length; i++) {
                HSSFCell cell5 = row3.createCell(i);
                // 加載單元格樣式
                cell5.setCellStyle(style2);
                cell5.setCellValue(fields[i]);
            }
            // 備注詳情
            HSSFRow row36 = sheet.createRow(1);
            row36.setHeightInPoints(18);
            HSSFCell cell36 = row36.createCell(0);
            // 加載單元格樣式
            HSSFCellStyle style36 = workbook.createCellStyle();
            style36.setAlignment(HSSFCellStyle.ALIGN_LEFT);// 水平居左
            style36.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 垂直居中
            cell36.setCellStyle(style36);
            HSSFFont font = workbook.createFont();
            font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 加粗字體
            font.setFontHeightInPoints((short) 16);
            style36.setFont(font);
            //cell36.setCellValue(data_batch);

            // 自適應中文
             
            // 4、操作單元格;寫入excel
            if (list != null && list.size() > 0) {
                for (int j = 0; j < list.size(); j++) {
                    Map<String, Object> map = list.get(j);
                    //Object bean = getBean(type, map);
                    HSSFRow row = sheet.createRow(j + 3);
                    int i=0;
                    for(Map.Entry<String,Object > entry:map.entrySet()){ 
                        String val="";
                        if((entry.getValue())!=null && (entry.getValue()) !="null"){
                            val=getValue( entry.getKey(),entry.getValue().toString());
                        }else{
                            val=" ";
                        }
                        //String val=() ? entry.getValue().toString() : "null";
                        HSSFCell cell = row.createCell(i);
                        i++;
                        cell.setCellValue(val);
                        logger.info("" + (j+3) + "行,第" + val+ "--賦值成功");
                    }
                    /*for (int i = 0; i < fields.length; i++) {
                        //String value = CommonUtil.getValue(bean, StringUtils.toCamelCase(fields[i]));
                        //value = getValue(fields[i], value);
                        //cell.setCellValue(value);
                        cell.setCellValue(list.get(j).get(i).toString());
                        //cell.setCellValue(list.get(j).get(i).toString());
                        
                    }*/
                    
                }
            }
            // 5、輸出
            workbook.write(outputStream);
            
            outputStream.flush();
            outputStream.close();
        
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    
    /**
     * 創建單元格樣式
     * 
     * @param workbook
     *            工作簿
     * @param fontSize
     *            字體大小
     * @return 單元格樣式
     */
    private static HSSFCellStyle createCellStyle(HSSFWorkbook workbook, short fontSize) {
        HSSFCellStyle style = workbook.createCellStyle();
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 水平居中
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 垂直居中
        // 創建字體
        HSSFFont font = workbook.createFont();
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 加粗字體
        font.setFontHeightInPoints(fontSize);
        // 加載字體
        style.setFont(font);
        return style;
    }
    
    
    public static String getValue(String field, String value) {
        if (field.equals("credLocation")) {
            if (value.equals("1")) {
                value = "庫內人員    ";
            }
            if (value.equals("2")) {
                value = "庫外人員";
            }
        }
        if (field.equals("chongfu")) {
            if (value.equals("1")) {
                value = "";
            }else{
                value = "";
            }
            
        }
       if (field.equals("days")) {
                if (value.contains("-")) {
                    String     value1 = "逾期"+value+"";
                    value=value1.replace("-", "");
                }else{
                    value = value+"天后保養";
                }
            }
       
       if (field.equals("recordStatus")) {
            if (value.equals("1")) {
                value = "故障報修";
            }else if (value.equals("2")){
                value = "已派工";
            }else if(value.equals("3")){
                value = "已出發";
            }else if(value.equals("4")){
                value = "到達現場";
            }else if(value.equals("5")){
                value = "維修完成";
            }else if(value.equals("6")){
                value = "服務評定";
            }
        }
        return value;
    }

    
    public static DecimalFormat getDf() {
        return df;
    }
    public static void setDf(DecimalFormat df) {
        ExcelUtil.df = df;
    }
    public static SimpleDateFormat getSdf() {
        return sdf;
    }
    public static void setSdf(SimpleDateFormat sdf) {
        ExcelUtil.sdf = sdf;
    }
    public static DecimalFormat getNf() {
        return nf;
    }
    public static void setNf(DecimalFormat nf) {
        ExcelUtil.nf = nf;
    }
    
    
    
     /**
     * 多行表頭
     * dataList:導出的數據;sheetName:表頭名稱; head0:表頭第一行列名;headnum0:第一行合並單元格的參數
     * head1:表頭第二行列名;headnum1:第二行合並單元格的參數;detail:導出的表體字段
     *
     */
     public  static void reportMergeXls(HttpServletRequest request,
                HttpServletResponse response, List<Map<String, Object>> dataList,
                String sheetName, String[] head0, String[] headnum0,
                String[] head1, String[] headnum1, String[] detail)
                throws Exception {
                HSSFWorkbook workbook = new HSSFWorkbook();
                     // 1、創建標題
                     String headRow = sheetName;
                     // 1.1、頭標題樣式
                     HSSFCellStyle headstyle = createCellStyle(workbook, (short) 18);
                     // 1.2、列標題樣式
                    HSSFCellStyle style1 = createCellStyle(workbook, (short) 13);
                     // 2、創建工作表
                     HSSFSheet sheet = workbook.createSheet(headRow);
                     // 設置默認列寬
                     sheet.setDefaultColumnWidth(22);
                     sheet.setDefaultRowHeightInPoints(22);
                     sheet.autoSizeColumn(1, true);
                     // 3、創建行
                     // 3.1、創建頭標題行;並且設置頭標題
                     HSSFRow row1 = sheet.createRow(0);
                     row1.setHeightInPoints(50);
                     HSSFCell cell1 = row1.createCell(0);
                     // 加載單元格樣式
                     cell1.setCellStyle(headstyle);
                     cell1.setCellValue(headRow);
                     // 3.1、創建副標題行;並且設置
                     HSSFRow row2 = sheet.createRow(1);
                     row2.setHeightInPoints(25);
                     HSSFCell cell2 = row2.createCell(0);
                     // 3.2、創建列標題行;並且設置列標題
                     HSSFRow row3 = sheet.createRow(2);
            // 第一行表頭標題
            sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, head0.length-1));
            HSSFRow row = sheet.createRow(0);
            row.setHeight((short) 0x349);
            HSSFCell cell = row.createCell(0);
            cell.setCellStyle(headstyle);
            CellUtil.setCellValue(cell, sheetName);
            // 第二行表頭列名
            row = sheet.createRow(1);
            for (int i = 0; i < head0.length; i++) {
                cell = row.createCell(i);
                cell.setCellValue(head0[i]);
                cell.setCellStyle(style1);
            }
            
          
         // 1.3、普通單元格樣式(中文)樣式
            HSSFCellStyle style2 =  workbook.createCellStyle();
             //HSSFCellStyle style36 = workbook.createCellStyle();
            style2.setAlignment(HSSFCellStyle.ALIGN_LEFT);// 水平居左
            style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 垂直居中
             HSSFFont font = workbook.createFont();
             font.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);// 加粗字體
             font.setFontHeightInPoints((short) 10);
             style2.setFont(font);
        
            //動態合並單元格
            for (int i = 0; i < headnum0.length; i++) {
                String[] temp = headnum0[i].split(",");
                Integer startrow = Integer.parseInt(temp[0]);
                Integer overrow = Integer.parseInt(temp[1]);
                Integer startcol = Integer.parseInt(temp[2]);
                Integer overcol = Integer.parseInt(temp[3]);
                sheet.addMergedRegion(new CellRangeAddress(startrow, overrow,
                        startcol, overcol));
            }
            //設置合並單元格的參數並初始化帶邊框的表頭(這樣做可以避免因為合並單元格后有的單元格的邊框顯示不出來)
            row = sheet.createRow(2);//因為下標從0開始,所以這里表示的是excel中的第三行
            for (int i = 0; i < head0.length; i++) { 
                cell = row.createCell(i);
                cell.setCellStyle(style1);//設置excel中第四行的1、2、7、8列的邊框
                if(i > 1 ) {
                    for (int j = 0; j < head1.length; j++) {
                        cell = row.createCell(j + 1);
                        cell.setCellValue(head1[j]);//給excel中第三行的3、4、5、6列賦值("溫度℃", "濕度%", "溫度℃", "濕度%")
                        cell.setCellStyle(style1);//設置excel中第三行的3、4、5、6列的邊框
                    } 
                } 
            }
            //動態合並單元格
            for (int i = 0; i < headnum1.length; i++) {
                String[] temp = headnum1[i].split(",");
                Integer startrow = Integer.parseInt(temp[0]);
                Integer overrow = Integer.parseInt(temp[1]);
                Integer startcol = Integer.parseInt(temp[2]);
                Integer overcol = Integer.parseInt(temp[3]);
                sheet.addMergedRegion(new CellRangeAddress(startrow, overrow,
                        startcol, overcol));
            }

            // 設置列值-內容
            for (int i = 0; i < dataList.size(); i++) {
                row = sheet.createRow(i + 3);//標題、時間、表頭字段共占了3行,所以在填充數據的時候要加3,也就是數據要從第4行開始填充
                for (int j = 0; j < detail.length; j++) {
                    Map tempmap = (HashMap) dataList.get(i);
                    Object data = tempmap.get(detail[j]);                
                    cell = row.createCell(j);
                    cell.setCellStyle(style2);
                    cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                    CellUtil.setCellValue(cell, data);
                }
            }
            String fileName = new String(sheetName.getBytes("gb2312"), "ISO8859-1");
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            workbook.write(baos);
            response.setContentType("application/x-download;charset=utf-8");
            response.addHeader("Content-Disposition", "attachment;filename="
                    + fileName + ".xls");
            OutputStream os = response.getOutputStream();
            ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
            byte[] b = new byte[1024];
            while ((bais.read(b)) > 0) {
                os.write(b);
            }
            bais.close();
            os.flush();
            os.close();
        }
}

公共類 CellUtil

package com.nskj.utils;

import java.math.BigDecimal;
import java.sql.Date;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.regex.Pattern;

import org.apache.poi.hssf.usermodel.HSSFCell;

public class CellUtil {
     public static String returnCellValue(HSSFCell cell){
            String cellvalue = "";
            if (null != cell) {   
                switch (cell.getCellType()) {   
                case HSSFCell.CELL_TYPE_NUMERIC: // 數字   
                    return String.valueOf(cell.getNumericCellValue()).trim();
                case HSSFCell.CELL_TYPE_STRING: // 字符串   
                    return String.valueOf(cell.getStringCellValue()).trim();
                case HSSFCell.CELL_TYPE_BOOLEAN: // Boolean   
                    return String.valueOf(cell.getBooleanCellValue()).trim();
                case HSSFCell.CELL_TYPE_FORMULA: // 公式   
                    return String.valueOf(cell.getCellFormula()).trim();  
                case HSSFCell.CELL_TYPE_BLANK: // 空值   
                    return "";  
                case HSSFCell.CELL_TYPE_ERROR: // 故障   
                    return ""; 
                default:   
                    return "";   
                }   
            } else {   
                
            }  
            return cellvalue;
        }
        
        //避免cell.setCellValue(checkOrderQmSave.getSellOrderNo())中參數為空就會報錯
        public static void setCellValue(HSSFCell cell, Object object){
            if(object == null){
                cell.setCellValue("");  
            }else{
                if (object instanceof String) {
                    cell.setCellValue(String.valueOf(object));  
                }else if(object instanceof Long){
                    Long temp = (Long)object;
                    String cellvalue = new DecimalFormat("#0.00").format(temp.doubleValue());
                    cell.setCellValue(cellvalue);  
                }else if(object instanceof Double){
                    Double temp = (Double)object;
                    String cellvalue = new DecimalFormat("#0.00").format(temp.doubleValue());
                    cell.setCellValue(cellvalue);  
                }else if(object instanceof Float){
                    Float temp = (Float)object;
                    String cellvalue = new DecimalFormat("#0.00").format(temp.doubleValue());
                    cell.setCellValue(cellvalue);  
                }else if(object instanceof Integer){
                    Integer temp = (Integer)object;
                    cell.setCellValue(temp.intValue());  
                }else if(object instanceof BigDecimal){
                    BigDecimal temp = (BigDecimal)object;
                    String cellvalue = new DecimalFormat("#").format(temp.doubleValue());
                    cell.setCellValue(cellvalue);  
                }else{
                    cell.setCellValue("");  
                }
            }
        }
        public static void setCellValue(HSSFCell cell, Object object, String model){
            if(object == null){
                cell.setCellValue("");  
            }else{
                if (object instanceof String) {
                    cell.setCellValue(String.valueOf(object));  
                }else if(object instanceof Long){
                    Long temp = (Long)object;
                    String cellvalue = new DecimalFormat("#0.00").format(temp.doubleValue());
                    cell.setCellValue(cellvalue);  
                }else if(object instanceof Double){
                    Double temp = (Double)object;
                    String cellvalue = new DecimalFormat("#0.00").format(temp.doubleValue());
                    cell.setCellValue(cellvalue);  
                }else if(object instanceof Float){
                    Float temp = (Float)object;
                    String cellvalue = new DecimalFormat("#0.00").format(temp.doubleValue());
                    cell.setCellValue(cellvalue);  
                }else if(object instanceof Integer){
                    Integer temp = (Integer)object;
                    cell.setCellValue(temp.intValue());  
                }else if(object instanceof BigDecimal){
                    BigDecimal temp = (BigDecimal)object;
                    String cellvalue = new DecimalFormat("#0.00").format(temp.doubleValue());
                    cell.setCellValue(cellvalue);  
                }else if(object instanceof java.sql.Date){
                    cell.setCellValue(new SimpleDateFormat(model).format(object));  
                }else if(object instanceof java.util.Date){
                    cell.setCellValue(new SimpleDateFormat(model).format(object));  
                }else{
                    cell.setCellValue("");  
                }
            }
        }
        public static void setCellValue(HSSFCell cell, String object){
            if(object == null){
                cell.setCellValue("");  
            }else{
                cell.setCellValue(object);  
            }
        }
        public static void setCellValue(HSSFCell cell, Long object){
            if(object == null){
                cell.setCellValue("");  
            }else{
                cell.setCellValue(object.doubleValue());  
            }
        }
        public static void setCellValue(HSSFCell cell, Double object){
            if(object == null){
                cell.setCellValue("");  
            }else{
                cell.setCellValue(object.doubleValue());  
            }
        }
        public static void setCellValue(HSSFCell cell, double object){
            
                cell.setCellValue(object);  
            
        }
        public static void setCellValue(HSSFCell cell, Date object, String model){
            if(object == null){
                cell.setCellValue("");  
            }else{
                cell.setCellValue(new SimpleDateFormat(model).format(object));  
            }
        }
        public static void setCellValue(HSSFCell cell, java.util.Date object, String model){
            if(object == null){
                cell.setCellValue("");  
            }else{
                cell.setCellValue(new SimpleDateFormat(model).format(object));  
            }
        }
        public static void setCellValue(HSSFCell cell, BigDecimal object){
            if(object == null){
                cell.setCellValue("");  
            }else{
                cell.setCellValue(object.toString());  
            }
        }
        
        //判斷EXCEL表格高度用 row.setHeight((short) CellUtil.getExcelCellAutoHeight(TAR_VAL_ALL_STRING, 280, 30));
        public static float getExcelCellAutoHeight(String str,float defaultRowHeight, int fontCountInline) {
            int defaultCount = 0;
            for (int i = 0; i < str.length(); i++) {
                int ff = getregex(str.substring(i, i + 1));
                defaultCount = defaultCount + ff;
            }
            if (defaultCount > fontCountInline){
                return ((int) (defaultCount / fontCountInline) + 1) * defaultRowHeight;//計算
            } else {
                return defaultRowHeight;
            }
        }
        public static int getregex(String charStr) {
            if("".equals(charStr) || charStr == null){
                return 1;
            }
            // 判斷是否為字母或字符
            if (Pattern.compile("^[A-Za-z0-9]+$").matcher(charStr).matches()) {
                return 1;
            }
            // 判斷是否為全角
            if (Pattern.compile("[\u4e00-\u9fa5]+$").matcher(charStr).matches()) {
                return 2;
            }
            //全角符號 及中文
            if (Pattern.compile("[^x00-xff]").matcher(charStr).matches()) {
                return 2;
            }
            return 1;
        }
}

前台頁面請求: 

這個地方在前台請求的時候 千萬不能用ajax   ,可以用一個簡單是 a 標簽鏈接到后台的控制器

<a class="aaaa"  href="${ctx}/export/exportMntOrgData">導出</a>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM