java 做Excel导出

Excel导出

本导出的思路:
1.Controller层接收导出请求,获取导出数据
2.导出部分根据 表头String[] titles导出需要展示的列,其中对象转Map部分主要是进行过滤为空和不显示 字段的数据,并生成新的导出数据进行导出
设置EXcel样式代码:
-package com.*.utilsExportExcell;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.*;
public class ExportInternalUtil {
private XSSFWorkbook wb = null;

private XSSFSheet sheet = null;
public ExportInternalUtil(XSSFWorkbook wb, XSSFSheet sheet) {
    this.wb = wb;
    this.sheet = sheet;
}

/**
 * 合并单元格后给合并后的单元格加边框
 * 
 * @param region
 * @param cs
 */
public void setRegionStyle(CellRangeAddress region, XSSFCellStyle cs) {

    int toprowNum = region.getFirstRow();
    for (int i = toprowNum; i <= region.getLastRow(); i++) {
        XSSFRow row = sheet.getRow(i);
        for (int j = region.getFirstColumn(); j <= region.getLastColumn(); j++) {
            XSSFCell cell = row.getCell(j);// XSSFCellUtil.getCell(row,
                                            // (short) j);
            cell.setCellStyle(cs);
        }
    }
}

/**
 * 设置表头的单元格样式
 * 
 * @return
 */
public XSSFCellStyle getHeadStyle() {
    // 创建单元格样式
    XSSFCellStyle cellStyle = wb.createCellStyle();
    // 设置单元格的背景颜色为淡蓝色
    cellStyle.setFillForegroundColor(HSSFColor.PALE_BLUE.index);
    cellStyle.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
    // 设置单元格居中对齐
    cellStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);
    // 设置单元格垂直居中对齐
     cellStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
    // 创建单元格内容显示不下时自动换行
     cellStyle.setWrapText(true);
     cellStyle.setWrapText(false);
    // 设置单元格字体样式
    XSSFFont font = wb.createFont();
    // 设置字体加粗
    font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
    font.setFontName("宋体");
    font.setFontHeight((short) 250);
    cellStyle.setFont(font);
    // 设置单元格边框为细线条
    cellStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);
    cellStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN);
    cellStyle.setBorderRight(XSSFCellStyle.BORDER_THIN);
    cellStyle.setBorderTop(XSSFCellStyle.BORDER_THIN);
    return cellStyle;
}

/**
 * 设置表体的单元格样式
 * 
 * @return
 */
public XSSFCellStyle getBodyStyle() {
    // 创建单元格样式
    XSSFCellStyle cellStyle = wb.createCellStyle();
    // 设置单元格居中对齐
    cellStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);

    // 设置单元格垂直居中对齐
   cellStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
    // 创建单元格内容显示不下时自动换行
   cellStyle.setWrapText(true);
    // 设置单元格字体样式
    XSSFFont font = wb.createFont();
    // 设置字体加粗
//    font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
    font.setFontName("宋体");
    font.setFontHeight((short) 200);

    cellStyle.setFont(font);
    // 设置单元格边框为细线条
    cellStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);
    cellStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN);
    cellStyle.setBorderRight(XSSFCellStyle.BORDER_THIN);
    cellStyle.setBorderTop(XSSFCellStyle.BORDER_THIN);
    return cellStyle;
}

}

导出部分代码:
package *.utilsExportExcell;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.apache.poi.hssf.util.CellRangeAddress;
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;
import org.springframework.beans.factory.annotation.Autowired;
import com.aqjcb.uap.aqjcbReport.defectFacCount.po.DefectFactoryCount;
public class ExportUtil {

public static void ExportExcel(String[] titles,List<Object> oj,String titletname,OutputStream outFile) {

ArrayList<Object> obj = new ArrayList<Object>();
 LinkedHashMap<String,String> title = new LinkedHashMap<String,String>(); 

for(int i=0;i<titles.length;i++){
   String dd = titles[i];
   String[] str = dd.split(":");
   title.put(str[0],str[1]);
}

  for(int i=0;i<oj.size();i++){
   Object a=oj.get(i);
   Map objmap =ObjectToMap.getValue(a);
   Map<String,String> colum = new HashMap<String,String>(); 
   for(String key : title.keySet()){        
       Object v = objmap.get(key);
         if(v==null){   v="";  }
       colum.put(key, v.toString()) ;     
   }
      obj.add(colum);
    }


    // 创建一个workbook 对应一个excel应用文件
    XSSFWorkbook workBook = new XSSFWorkbook();
    // 在workbook中添加一个sheet,对应Excel文件中的sheet
    //Sheet名称,可以自定义中文名称
    XSSFSheet sheet = workBook.createSheet(titletname);
    ExportInternalUtil exportUtil = new ExportInternalUtil(workBook, sheet);
    XSSFCellStyle headStyle = exportUtil.getHeadStyle();
    XSSFCellStyle bodyStyle = exportUtil.getBodyStyle();
    // 构建标题
    XSSFRow titleRow = sheet.createRow((int) 0);  
    XSSFCell titleCell1 = titleRow.createCell((short) 0);
    titleCell1.setCellStyle(headStyle);
    titleCell1.setCellValue(titletname);
    sheet.addMergedRegion(new CellRangeAddress(0,  0, 0, titles.length-1));
    sheet.setColumnWidth(0, 30 * 256);  //设置第一列列宽
    sheet.setColumnWidth(titles.length-1, 15 * 256);
    sheet.setColumnWidth(titles.length-2,15 * 256);
 // 输出表头
    XSSFRow headRow = sheet.createRow(1);
    XSSFCell cell = null;

    for (int i = 0; i < titles.length; i++) {
        cell = headRow.createCell(i);
        cell.setCellStyle(bodyStyle);
        String titleContent =titles[i].split(":")[1];
        cell.setCellValue(titleContent);
    }
    System.out.println("输出行数list.size()"+obj.size());
    // 构建表体数据
    for (int j = 0; j < obj.size(); j++) {

          XSSFRow bodyRow = sheet.createRow(j + 2);
           Map df = (Map) obj.get(j);        
          for (int i = 0; i < titles.length; i++) {        
              cell = bodyRow.createCell(i);
              cell.setCellStyle(bodyStyle);
              String key=titles[i].split(":")[0];
              cell.setCellValue(df.get(key).toString());
       } 
    }

    try {

        workBook.write(outFile);
        outFile.flush();
        outFile.close();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            outFile.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

}

对象转Map部分代码:
package com.*.utilsExportExcell;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class ObjectToMap {

 public static Map getValue(Object thisObj)  
    {  
      Map<String, Object> map = new HashMap<String, Object>();  
        Class<?> c;  
      try  
      {  
        c = Class.forName(thisObj.getClass().getName());  
        Method[] m = c.getMethods();  
        for (int i = 0; i < m.length; i++)  
        {  
          String method = m[i].getName();  
          if (method.startsWith("get"))  
          {  
            try{  
            Object value = m[i].invoke(thisObj);  
            if (value != null)  
            {  
              String key=method.substring(3);  
              key=key.substring(0,1).toUpperCase()+key.substring(1);  
              map.put(key, value);  
            }
            }catch (Exception e) {  
              // TODO: handle exception  
              System.out.println("error:"+method);  
            }  
          }  
        }  
      }  
      catch (Exception e)  
      {  
        // TODO: handle exception  
        e.printStackTrace();  
      }  
      return map;  
    }  

}

Controller层代码
@RequestMapping(“/expotExcell”)
public @ResponseBody
void exportExcel(HttpServletResponse response,HttpServletRequest request) {

    try {
        HttpSession session = request.getSession();
        String fileName=new String(("表").getBytes("gb2312"), "iso8859-1")+ ".xlsx";
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        response.setCharacterEncoding("utf-8");
             //需要导出的列
        String[] titles = { "Pname:单位", "EquipNum:设备总数","Starttime:开始时间","Stoptime:结束时间" };
              //需要导出的List集
        List<Object> list=  (List<Object>) session.getAttribute("queryResult");  

    /**********************合计********start*************************/ 

//思路:1.a.将需要导出的list 循环求和 b.sql查询合计的值
2.new 新的Bean,将bean的对应字段set进合计的值
3.将该bean添加到list中 list.add(hj);

  /**********************合计***********end**********************/            

        OutputStream outFile=response.getOutputStream(); 
        ExportUtil.ExportExcel(titles,list ,"表",outFile);

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

本文中部分代码参考别人贡献


猜你喜欢

转载自blog.csdn.net/qq_28014495/article/details/53218135