Excel的导入和导出功能实现

工作中经常会用到excel的导入和导出功能,这里我提供导入和导出类。

导入类(需要注意的地方我注释里面写好了):

[java]  view plain  copy
  1. package cn.teacheredu.utils;  
  2.   
  3. import java.io.InputStream;  
  4. import java.text.SimpleDateFormat;  
  5. import java.util.ArrayList;  
  6. import java.util.Arrays;  
  7. import java.util.Date;  
  8. import java.util.List;  
  9. import java.util.regex.Matcher;  
  10. import java.util.regex.Pattern;  
  11.   
  12. import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
  13. import org.apache.poi.ss.usermodel.Cell;  
  14. import org.apache.poi.ss.usermodel.DateUtil;  
  15. import org.apache.poi.ss.usermodel.Row;  
  16. import org.apache.poi.ss.usermodel.Sheet;  
  17. import org.apache.poi.ss.usermodel.Workbook;  
  18. import org.apache.poi.xssf.usermodel.XSSFWorkbook;  
  19.   
  20. /** 
  21.  * 被解析的Excel最好是什么样的呢?   
  22.  * 单元格最好都是文本格式,保存数据前自己去转换,不用poi带的转换。 
  23.  * 第一列 和最后一列 必须是必填字段!!!这样的你用我这个Util,得到的List就很准确了,不会出现多余的行或列。 
  24.  * @author TMACJ 
  25.  * @version 0.000000.002899 
  26.  */  
  27. public class ImportExcelUtil {  
  28.     private final static String excel2003L =".xls";    //2003- 版本的excel  
  29.     private final static String excel2007U =".xlsx";   //2007+ 版本的excel  
  30.       
  31.     static SimpleDateFormat sFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
  32.     static short[] yyyyMMdd = {14315758179184185186187188};  
  33.     static short[] HHmmss = {2032190191192};  
  34.     static List<short[]> yyyyMMddList = Arrays.asList(yyyyMMdd);  
  35.     static List<short[]> hhMMssList = Arrays.asList(HHmmss);  
  36.     /** 
  37.      * 描述:获取IO流中的数据,组装成List<List<Object>>对象 
  38.      * @param in,fileName 
  39.      * @return 
  40.      * @throws IOException  
  41.      */  
  42.     public  List<List<String>> getBankListByExcel(InputStream in,String fileName) throws Exception{  
  43.         List<List<String>> list = null;  
  44.           
  45.         //创建Excel工作薄  
  46.         Workbook work = this.getWorkbook(in,fileName);  
  47.         if(null == work){  
  48.             throw new Exception("创建Excel工作薄为空!");  
  49.         }  
  50.         Sheet sheet = null;  
  51.         Row row = null;  
  52.         Cell cell = null;  
  53.           
  54.         list = new ArrayList<List<String>>();  
  55.         //遍历Excel中所有的sheet  
  56.         for (int i = 0; i < work.getNumberOfSheets(); i++) {  
  57.             sheet = work.getSheetAt(i);  
  58.             if(sheet==null){continue;}  
  59.             int totalCell = sheet.getRow(0).getPhysicalNumberOfCells();//标题行一共有多少列  
  60.             //遍历当前sheet中的所有行  
  61.             for (int j = sheet.getFirstRowNum(); j < sheet.getLastRowNum()+1; j++) {  
  62.                 row = sheet.getRow(j);  
  63.                 if(row==null || validateRow(row) || row.getPhysicalNumberOfCells() < totalCell){continue;} //3个条件,有一个为true就不会往list里加,不仅过滤空行还过滤了列数不够的行,这点要注意,要求表中前后的列都是必填的。  
  64.                 //遍历所有的列  
  65.                 List<String> li = new ArrayList<String>();  
  66.                 for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {  
  67.                     cell = row.getCell(y);  
  68.                     li.add(this.getCellData(cell));  
  69.                 }  
  70.                 list.add(li);  
  71.             }  
  72.             // 简单起见,这里只解析第一个工作簿!  
  73.             break;  
  74.         }  
  75.         work.close();  
  76.         return list;  
  77.     }  
  78.     // 过滤空行,(其中一行的数据的确都为空,可是其原本的格式还在,并没有连带删除,这样计算出来的行数就不真实,比真实的大)  
  79.     private boolean validateRow(Row row) throws Exception{  
  80. //      for (Cell cell : row) {  
  81. //            
  82. //      }  
  83.         //只判断第一列。第一列为空就代表这行的数据无效  
  84.         if (row.getCell(0).getCellType() == Cell.CELL_TYPE_BLANK || "".equals(this.getCellData(row.getCell(0)))) {  
  85.             return true;  
  86.         }  
  87.         return false;//不是空行  
  88.     }  
  89.     /** 
  90.      * 描述:根据文件后缀,自适应上传文件的版本  
  91.      * @param inStr,fileName 
  92.      * @return 
  93.      * @throws Exception 
  94.      */  
  95.     public  Workbook getWorkbook(InputStream inStr,String fileType) throws Exception{  
  96.         Workbook wb = null;  
  97.         if(excel2003L.equals(fileType)){  
  98.             wb = new HSSFWorkbook(inStr);  //2003-  
  99.         }else if(excel2007U.equals(fileType)){  
  100.             wb = new XSSFWorkbook(inStr);  //2007+  
  101.         }else{  
  102.             throw new Exception("解析的文件格式有误!");  
  103.         }  
  104.         return wb;  
  105.     }  
  106.       
  107.     /** 
  108.      * 获取单元中值(字符串类型) 
  109.      * 
  110.      * @param cell 
  111.      * @return 
  112.      * @throws Exception  
  113.      */  
  114.     public String getCellData(Cell cell) throws Exception {  
  115.         String cellValue = "";  
  116.         if (cell != null) {  
  117.             try {  
  118.                 switch (cell.getCellType()) {  
  119.                     case Cell.CELL_TYPE_BLANK://空白  
  120.                         cellValue = "";  
  121.                         break;  
  122.                     case Cell.CELL_TYPE_NUMERIC: //数值型 0----日期类型也是数值型的一种  
  123.                         if (DateUtil.isCellDateFormatted(cell)) {  
  124.                             short format = cell.getCellStyle().getDataFormat();  
  125.    
  126.                             if (yyyyMMddList.contains(format)) {  
  127.                                 sFormat = new SimpleDateFormat("yyyy-MM-dd");  
  128.                             } else if (hhMMssList.contains(format)) {  
  129.                                 sFormat = new SimpleDateFormat("HH:mm:ss");  
  130.                             }  
  131.                             Date date = cell.getDateCellValue();  
  132.                             cellValue = sFormat.format(date);  
  133.                         } else {  
  134.                             cell.setCellType(Cell.CELL_TYPE_STRING);  
  135.                             cellValue = replaceBlank(cell.getStringCellValue());  
  136.                             //Double numberDate = new BigDecimal(cell.getNumericCellValue()).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();//似乎还是有点问题  
  137.                             //cellValue = numberDate + "";  
  138.                         }  
  139.                         break;  
  140.                     case Cell.CELL_TYPE_STRING: //字符串型 1  
  141.                         cellValue = replaceBlank(cell.getStringCellValue());  
  142.                         break;  
  143.                     case Cell.CELL_TYPE_FORMULA: //公式型 2  
  144.                         cell.setCellType(Cell.CELL_TYPE_STRING);  
  145.                         cellValue = replaceBlank(cell.getStringCellValue());  
  146.                         break;  
  147.                     case Cell.CELL_TYPE_BOOLEAN: //布尔型 4  
  148.                         cellValue = String.valueOf(cell.getBooleanCellValue());  
  149.                         break;  
  150.                     case Cell.CELL_TYPE_ERROR: //错误 5  
  151.                         cellValue = "!#REF!";  
  152.                         break;  
  153.                 }  
  154.             } catch (Exception e) {  
  155.                 throw new Exception("读取Excel单元格数据出错:" + e.getMessage());  
  156.             }  
  157.         }  
  158.         return cellValue;  
  159.     }  
  160.       
  161.     public static String replaceBlank(String source) {  
  162.         String dest = "";  
  163.         if (source != null) {  
  164.             Pattern p = Pattern.compile("\t|\r|\n");  
  165.             Matcher m = p.matcher(source);  
  166.             dest = m.replaceAll("");  
  167.         }  
  168.         return dest.trim();  
  169.     }  
  170.       
  171. }  

导出类(.XLS格式):

[java]  view plain  copy
  1. package cn.teacheredu.utils;  
  2.   
  3. import java.io.OutputStream;  
  4. import java.net.URLEncoder;  
  5. import java.util.ArrayList;  
  6. import java.util.Date;  
  7. import java.util.List;  
  8.   
  9. import javax.servlet.http.HttpServletRequest;  
  10. import javax.servlet.http.HttpServletResponse;  
  11.   
  12. import org.apache.commons.lang.StringUtils;  
  13. import org.apache.commons.lang3.time.DateFormatUtils;  
  14. import org.apache.poi.hssf.usermodel.HSSFCell;  
  15. import org.apache.poi.hssf.usermodel.HSSFCellStyle;  
  16. import org.apache.poi.hssf.usermodel.HSSFFont;  
  17. import org.apache.poi.hssf.usermodel.HSSFRichTextString;  
  18. import org.apache.poi.hssf.usermodel.HSSFRow;  
  19. import org.apache.poi.hssf.usermodel.HSSFSheet;  
  20. import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
  21. import org.apache.poi.hssf.util.HSSFColor;  
  22. import org.apache.poi.ss.util.CellRangeAddress;  
  23.   
  24. /** 
  25.  * 通用的导出Excel类,如果需要自定义格式的,参照此类自己再写类或方法来实现 
  26.  * dataList里的每一个Object数组一个元素(object[0])都是序号,不可放真实数据 
  27.  * @author<span style="white-space:pre;">   </span>TMACJ 
  28.  */  
  29. public class ExportExcelUtil {  
  30.       
  31.     private String title; // 导出表格的表名  
  32.       
  33.     private String[] rowName;// 导出表格的列名  
  34.       
  35.     private List<Object[]>  dataList = new ArrayList<Object[]>(); // 对象数组的List集合  
  36.       
  37.     private HttpServletResponse  response;  
  38.       
  39.     private HttpServletRequest request;  
  40.   
  41.       
  42.     /** 
  43.      * 实例化导出类 
  44.      * @param title  导出表格的表名,最好是英文,中文可能出现乱码 
  45.      * @param rowName 导出表格的列名数组 
  46.      * @param dataList 对象数组的List集合 
  47.      * @param response 
  48.      */  
  49.     public ExportExcelUtil(String title,String[] rowName,List<Object[]>  dataList, HttpServletRequest request, HttpServletResponse  response){  
  50.         this.title=title;  
  51.         this.rowName=rowName;  
  52.         this.dataList=dataList;  
  53.         this.response = response;  
  54.         this.request = request;  
  55.     }  
  56.       
  57.     // 导出数据  
  58.     public void exportData() throws Exception{  
  59.         HSSFWorkbook workbook =new HSSFWorkbook(); // 创建一个excel对象  
  60.         HSSFSheet sheet =workbook.createSheet(title); // 创建表格  
  61.           
  62.         //sheet.setDefaultRowHeightInPoints(18.5f);  
  63.           
  64.         // sheet样式定义  
  65.         HSSFCellStyle columnTopStyle = this.getColumnTopStyle(workbook,16); // 头样式  
  66.         HSSFCellStyle columnStyle = this.getColumnStyle(workbook,14); // 标题样式  
  67.         HSSFCellStyle style = this.getStyle(workbook,11);  // 单元格样式  
  68.   
  69.         sheet.addMergedRegion(new CellRangeAddress(000, (rowName.length-1)));// 合并第一行的所有列  
  70.         // 产生表格标题行  
  71.         HSSFRow rowm  =sheet.createRow(0);  // 行  
  72.         rowm.setHeightInPoints(26f);  
  73.         HSSFCell cellTiltle =rowm.createCell(0);  // 单元格  
  74.           
  75.         cellTiltle.setCellStyle(columnTopStyle);  
  76.         cellTiltle.setCellValue(title);  
  77.               
  78.         int columnNum = rowName.length;  // 表格列的长度  
  79.         HSSFRow rowRowName = sheet.createRow(1);  // 在第二行创建行  
  80.         HSSFCellStyle cells =workbook.createCellStyle();  
  81.         cells.setBottomBorderColor(HSSFColor.BLACK.index);    
  82.         rowRowName.setRowStyle(cells);  
  83.               
  84.         // 循环 将列名放进去  
  85.         for (int i = 0; i < columnNum; i++) {  
  86.             HSSFCell cellRowName = rowRowName.createCell(i);  
  87.             cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING); // 单元格类型  
  88.             HSSFRichTextString text = new HSSFRichTextString(rowName[i]);  // 得到列的值  
  89.             cellRowName.setCellValue(text); // 设置列的值  
  90.             cellRowName.setCellStyle(columnStyle); // 样式  
  91.         }  
  92.               
  93.         // 将查询到的数据设置到对应的单元格中  
  94.         for (int i = 0; i < dataList.size(); i++) {  
  95.             Object[] obj = dataList.get(i);//遍历每个对象  
  96.             HSSFRow row = sheet.createRow(i+2);//创建所需的行数  
  97.             for (int j = 0; j < obj.length; j++) {  
  98.                  HSSFCell  cell = null;   //设置单元格的数据类型   
  99.                  if(j==0){  
  100.                      // 第一列设置为序号  
  101.                      cell = row.createCell(j,HSSFCell.CELL_TYPE_NUMERIC);  
  102.                      cell.setCellValue(i+1);  
  103.                  }else{  
  104.                      cell = row.createCell(j,HSSFCell.CELL_TYPE_STRING);  
  105.                      if(!"".equals(obj[j]) && obj[j] != null){  
  106.                          cell.setCellValue(obj[j].toString());  //设置单元格的值    
  107.                      }else{  
  108.                          cell.setCellValue("  ");  
  109.                      }    
  110.                  }  
  111.                  cell.setCellStyle(style); // 样式  
  112.             }  
  113.         }  
  114.           
  115.         //  让列宽随着导出的列长自动适应,但是对中文支持不是很好  也可能在linux(无图形环境的操作系统)下报错,报错再说  
  116.         for (int i = 0; i < columnNum; i++) {  
  117.             sheet.autoSizeColumn(i);  
  118.             sheet.setColumnWidth(i, sheet.getColumnWidth(i)+888);//适当再宽点  
  119.         }  
  120.           
  121.         if(workbook !=null){  
  122.             // 输出到服务器上  
  123. //          FileOutputStream fileOutputStream = new FileOutputStream("D:/user.xls");  
  124. //          workbook.write(fileOutputStream);//将数据写出去  
  125. //          fileOutputStream.close();//关闭输出流  
  126.             // 输出到用户浏览器上  
  127.             OutputStream out = response.getOutputStream();  
  128.             try {  
  129.                 // excel 表文件名  
  130.                 String fileName = title + DateFormatUtils.format(new Date(), "yyyyMMddHHmmss") + ".xls";  
  131.                 String fileName11 = "";  
  132.                 String userAgent = request.getHeader("USER-AGENT");  
  133.                 if(StringUtils.contains(userAgent, "Firefox") || StringUtils.contains(userAgent, "firefox")){//火狐浏览器    
  134.                     fileName11 = new String(fileName.getBytes(), "ISO8859-1");  
  135.                 }else{    
  136.                     fileName11 = URLEncoder.encode(fileName,"UTF-8");//其他浏览器    
  137.                 }  
  138.                 String headStr = "attachment; filename=\"" + fileName11 + "\"";  
  139.                 response.setContentType("APPLICATION/OCTET-STREAM");  
  140.                 response.setCharacterEncoding("UTF-8");  
  141.                 response.setHeader("Content-Disposition", headStr);  
  142.                 workbook.write(out);  
  143.                 out.flush();  
  144.                 workbook.close();  
  145.             } catch (Exception e) {  
  146.                 throw e;  
  147.             } finally {  
  148.                 if (null != out) {  
  149.                     out.close();  
  150.                 }  
  151.             }  
  152.         }    
  153.     }    
  154.               
  155.     public HSSFCellStyle getColumnTopStyle(HSSFWorkbook workbook,int fontSize) {    
  156.         // 设置字体  
  157.         HSSFFont font = workbook.createFont();  
  158.         //设置字体大小  
  159.         font.setFontHeightInPoints((short)fontSize);  
  160.         //字体加粗  
  161.         font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);  
  162.         //设置字体名字   
  163.         font.setFontName("宋体");  
  164.         //设置样式;  
  165.         HSSFCellStyle style = workbook.createCellStyle();  
  166.         //在样式用应用设置的字体;      
  167.         style.setFont(font);  
  168.         //设置自动换行;  
  169.         style.setWrapText(false);  
  170.         //设置水平对齐的样式为居中对齐;  
  171.         style.setAlignment(HSSFCellStyle.ALIGN_CENTER);  
  172.         //设置垂直对齐的样式为居中对齐;  
  173.         style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);  
  174.         return style;  
  175.     }    
  176.       
  177.     public HSSFCellStyle getColumnStyle(HSSFWorkbook workbook,int fontSize) {    
  178.         // 设置字体  
  179.         HSSFFont font = workbook.createFont();  
  180.         //设置字体大小  
  181.         font.setFontHeightInPoints((short)fontSize);  
  182.         //字体加粗  
  183.         font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);  
  184.         //设置字体名字   
  185.         font.setFontName("宋体");  
  186.         //设置样式;  
  187.         HSSFCellStyle style = workbook.createCellStyle();  
  188.         //设置底边框;  
  189.         style.setBorderBottom(HSSFCellStyle.BORDER_THIN);  
  190.         //设置底边框颜色;  
  191.         style.setBottomBorderColor(HSSFColor.BLACK.index);  
  192.         //设置左边框;  
  193.         style.setBorderLeft(HSSFCellStyle.BORDER_THIN);  
  194.         //设置左边框颜色;  
  195.         style.setLeftBorderColor(HSSFColor.BLACK.index);  
  196.         //设置右边框;  
  197.         style.setBorderRight(HSSFCellStyle.BORDER_THIN);  
  198.         //设置右边框颜色;  
  199.         style.setRightBorderColor(HSSFColor.BLACK.index);  
  200.         //设置顶边框;  
  201.         style.setBorderTop(HSSFCellStyle.BORDER_THIN);  
  202.         //设置顶边框颜色;  
  203.         style.setTopBorderColor(HSSFColor.BLACK.index);  
  204.         //在样式用应用设置的字体;      
  205.         style.setFont(font);  
  206.         //设置自动换行;  
  207.         style.setWrapText(false);  
  208.         //设置水平对齐的样式为居中对齐;  
  209.         style.setAlignment(HSSFCellStyle.ALIGN_CENTER);  
  210.         //设置垂直对齐的样式为居中对齐;  
  211.         style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);  
  212.         return style;  
  213.     }  
  214.       
  215.     public HSSFCellStyle getStyle(HSSFWorkbook workbook,int fontSize) {  
  216.         //设置字体  
  217.         HSSFFont font = workbook.createFont();  
  218.         //设置字体大小  
  219.         font.setFontHeightInPoints((short)fontSize);  
  220.         //字体加粗    
  221.         //font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);    
  222.         //设置字体名字     
  223.         font.setFontName("宋体");  
  224.         //设置样式;  
  225.         HSSFCellStyle style = workbook.createCellStyle();  
  226.         //设置底边框;  
  227.         style.setBorderBottom(HSSFCellStyle.BORDER_THIN);  
  228.         //设置底边框颜色;  
  229.         style.setBottomBorderColor(HSSFColor.BLACK.index);  
  230.         //设置左边框;       
  231.         style.setBorderLeft(HSSFCellStyle.BORDER_THIN);  
  232.         //设置左边框颜色;     
  233.         style.setLeftBorderColor(HSSFColor.BLACK.index);  
  234.         //设置右边框;     
  235.         style.setBorderRight(HSSFCellStyle.BORDER_THIN);  
  236.         //设置右边框颜色;     
  237.         style.setRightBorderColor(HSSFColor.BLACK.index);  
  238.         //设置顶边框;     
  239.         style.setBorderTop(HSSFCellStyle.BORDER_THIN);  
  240.         //设置顶边框颜色;      
  241.         style.setTopBorderColor(HSSFColor.BLACK.index);  
  242.         //在样式用应用设置的字体;  
  243.         style.setFont(font);  
  244.         //设置自动换行;     
  245.         style.setWrapText(false);  
  246.         //设置水平对齐的样式为居中对齐;  
  247.         style.setAlignment(HSSFCellStyle.ALIGN_CENTER);  
  248.         //设置垂直对齐的样式为居中对齐;  
  249.         style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);  
  250.            
  251.         return style;  
  252.     }  
  253. }  


导出类(.xlsx格式):

[java]  view plain  copy
  1. package cn.teacheredu.utils;  
  2.   
  3. import java.io.OutputStream;  
  4. import java.net.URLEncoder;  
  5. import java.util.ArrayList;  
  6. import java.util.Date;  
  7. import java.util.List;  
  8.   
  9. import javax.servlet.http.HttpServletRequest;  
  10. import javax.servlet.http.HttpServletResponse;  
  11.   
  12. import org.apache.commons.lang.StringUtils;  
  13. import org.apache.commons.lang3.time.DateFormatUtils;  
  14. import org.apache.poi.hssf.util.HSSFColor;  
  15. import org.apache.poi.ss.usermodel.CellStyle;  
  16. import org.apache.poi.ss.usermodel.Font;  
  17. import org.apache.poi.ss.util.CellRangeAddress;  
  18. import org.apache.poi.xssf.streaming.SXSSFCell;  
  19. import org.apache.poi.xssf.streaming.SXSSFRow;  
  20. import org.apache.poi.xssf.streaming.SXSSFSheet;  
  21. import org.apache.poi.xssf.streaming.SXSSFWorkbook;  
  22. import org.apache.poi.xssf.usermodel.XSSFRichTextString;  
  23.   
  24. /** 
  25.  * 通用的导出Excel类,(Excel 2007 OOXML (.xlsx)格式 )如果需要自定义格式的,参照此类自己再写类或方法来实现 
  26.  * dataList里的每一个Object数组一个元素(object[0])都是序号,不可放真实数据 
  27.  * @author Zhaojie 
  28.  */  
  29. public class ExportExcelUtil2 {  
  30.       
  31.     private String title; // 导出表格的表名  
  32.       
  33.     private String[] rowName;// 导出表格的列名  
  34.       
  35.     private List<Object[]>  dataList = new ArrayList<Object[]>(); // 对象数组的List集合  
  36.       
  37.     private HttpServletResponse  response;  
  38.       
  39.     private HttpServletRequest request;  
  40.   
  41.       
  42.     /** 
  43.      * 实例化导出类 
  44.      * @param title  导出表格的表名,最好是英文,中文可能出现乱码 
  45.      * @param rowName 导出表格的列名数组 
  46.      * @param dataList 对象数组的List集合 
  47.      * @param response 
  48.      */  
  49.     public ExportExcelUtil2(String title,String[] rowName,List<Object[]>  dataList, HttpServletRequest request, HttpServletResponse  response){  
  50.         this.title=title;  
  51.         this.rowName=rowName;  
  52.         this.dataList=dataList;  
  53.         this.response = response;  
  54.         this.request = request;  
  55.     }  
  56.       
  57.     // 导出数据  
  58.     public void exportData() throws Exception{  
  59.         SXSSFWorkbook workbook = new SXSSFWorkbook();//声明一个工作薄 Excel 2007 OOXML (.xlsx)格式  
  60.         SXSSFSheet sheet = workbook.createSheet(title); // 创建表格  
  61.         for(int i = 1;i<rowName.length;i++){ //根据列名设置每一列的宽度  
  62.             int length = rowName[i].toString().length();  
  63.             sheet.setColumnWidth(i, 2*(length+1)*256);  
  64.         }  
  65.         //sheet.setDefaultRowHeightInPoints(18.5f);  
  66.           
  67.         // sheet样式定义  
  68.         CellStyle columnTopStyle = this.getColumnTopStyle(workbook,14); // 头样式  
  69.         CellStyle columnStyle = this.getColumnStyle(workbook,12); // 标题样式  
  70.         CellStyle style = this.getStyle(workbook,11);  // 单元格样式  
  71.           
  72.         // 产生表格标题行  
  73.         sheet.addMergedRegion(new CellRangeAddress(000, (rowName.length-1)));// 合并第一行的所有列  
  74.         SXSSFRow rowm  = sheet.createRow(0);  // 行  
  75.         rowm.setHeightInPoints(31f);  
  76.         SXSSFCell cellTiltle = rowm.createCell(0);  // 单元格  
  77.         cellTiltle.setCellStyle(columnTopStyle);  
  78.         cellTiltle.setCellValue(title);  
  79.           
  80.         // 产生第二行(列名)  
  81.         int columnNum = rowName.length;  // 表格列的长度  
  82.         SXSSFRow rowRowName = sheet.createRow(1);  // 在第二行创建行  
  83.         rowRowName.setHeightInPoints(21f);  
  84.         CellStyle cells = workbook.createCellStyle();  
  85.         cells.setBottomBorderColor(HSSFColor.BLACK.index);    
  86.         rowRowName.setRowStyle(cells);  
  87.         for (int i = 0; i < columnNum; i++) {  
  88.             SXSSFCell cellRowName = rowRowName.createCell(i);  
  89.             cellRowName.setCellType(SXSSFCell.CELL_TYPE_STRING); // 单元格类型  
  90.             XSSFRichTextString  text = new XSSFRichTextString(rowName[i]);  // 得到列的值  
  91.             cellRowName.setCellValue(text); // 设置列的值  
  92.             cellRowName.setCellStyle(columnStyle); // 样式  
  93.         }  
  94.               
  95.         // 产生其它行(将数据列表设置到对应的单元格中)注意:默认添加了第一列的序号,如果不要可以注释掉  
  96.         for (int i = 0; i < dataList.size(); i++) {  
  97.             Object[] obj = dataList.get(i);//遍历每个对象  
  98.             SXSSFRow row = sheet.createRow(i+2);//创建所需的行数  
  99.             row.setHeightInPoints(17.25f);  
  100.             for (int j = 0; j < obj.length; j++) {  
  101.                 SXSSFCell  cell = null;   //设置单元格的数据类型   
  102.                  if(j==0){  
  103.                      // 第一列设置为序号  
  104.                      cell = row.createCell(j,SXSSFCell.CELL_TYPE_NUMERIC);  
  105.                      cell.setCellValue(i+1);  
  106.                  }else{  
  107.                      cell = row.createCell(j,SXSSFCell.CELL_TYPE_STRING);  
  108.                      if(!"".equals(obj[j]) && obj[j] != null){  
  109.                          cell.setCellValue(obj[j].toString());  //设置单元格的值    
  110.                      }else{  
  111.                          cell.setCellValue("  ");  
  112.                      }    
  113.                  }  
  114.                  cell.setCellStyle(style); // 样式  
  115.             }  
  116.         }  
  117.           
  118.         //  让列宽随着导出的列长自动适应,但是对中文支持不是很好  也可能在linux(无图形环境的操作系统)下报错,报错再说  
  119. //      for (int i = 0; i < columnNum; i++) {  
  120. //          sheet.autoSizeColumn(i);  
  121. //          sheet.setColumnWidth(i, sheet.getColumnWidth(i)+888);//适当再宽点  
  122. //      }  
  123.           
  124.         if(workbook !=null){  
  125.             // 输出到服务器上  
  126. //          FileOutputStream fileOutputStream = new FileOutputStream("D:/user.xls");  
  127. //          workbook.write(fileOutputStream);//将数据写出去  
  128. //          fileOutputStream.close();//关闭输出流  
  129.             // 输出到用户浏览器上  
  130.             OutputStream out = response.getOutputStream();  
  131.             try {  
  132.                 // excel 表文件名  
  133.                 String fileName = title + DateFormatUtils.format(new Date(), "yyyyMMddHHmmss") + ".xlsx";  
  134.                 String fileName11 = "";  
  135.                 String userAgent = request.getHeader("USER-AGENT");  
  136.                 if(StringUtils.contains(userAgent, "Firefox") || StringUtils.contains(userAgent, "firefox")){//火狐浏览器    
  137.                     fileName11 = new String(fileName.getBytes(), "ISO8859-1");  
  138.                 }else{    
  139.                     fileName11 = URLEncoder.encode(fileName,"UTF-8");//其他浏览器    
  140.                 }  
  141.                 String headStr = "attachment; filename=\"" + fileName11 + "\"";  
  142.                 response.setContentType("APPLICATION/OCTET-STREAM");  
  143.                 response.setCharacterEncoding("UTF-8");  
  144.                 response.setHeader("Content-Disposition", headStr);  
  145.                 workbook.write(out);  
  146.                 out.flush();  
  147.                 workbook.close();  
  148.                 workbook.dispose();  
  149.             } catch (Exception e) {  
  150.                 throw e;  
  151.             } finally {  
  152.                 if (null != out) {  
  153.                     out.close();  
  154.                 }  
  155.             }  
  156.         }    
  157.     }    
  158.               
  159.     public CellStyle getColumnTopStyle(SXSSFWorkbook workbook,int fontSize) {    
  160.         // 设置字体  
  161.         Font font = workbook.createFont();  
  162.         //设置字体大小  
  163.         font.setFontHeightInPoints((short)fontSize);  
  164.         //字体加粗  
  165.         font.setBoldweight(Font.BOLDWEIGHT_BOLD);  
  166.         //设置字体名字   
  167.         font.setFontName("宋体");  
  168.         //设置样式;  
  169.         CellStyle style = workbook.createCellStyle();  
  170.         //在样式用应用设置的字体;      
  171.         style.setFont(font);  
  172.         //设置自动换行;  
  173.         style.setWrapText(false);  
  174.         //设置水平对齐的样式为居中对齐;  
  175.         style.setAlignment(CellStyle.ALIGN_CENTER);  
  176.         //设置垂直对齐的样式为居中对齐;  
  177.         style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);  
  178.         return style;  
  179.     }    
  180.       
  181.     public CellStyle getColumnStyle(SXSSFWorkbook workbook,int fontSize) {    
  182.         // 设置字体  
  183.         Font font = workbook.createFont();  
  184.         //设置字体大小  
  185.         font.setFontHeightInPoints((short)fontSize);  
  186.         //字体加粗  
  187.         font.setBoldweight(Font.BOLDWEIGHT_BOLD);  
  188.         //设置字体名字   
  189.         font.setFontName("宋体");  
  190.         //设置样式;  
  191.         CellStyle style = workbook.createCellStyle();  
  192.         //设置底边框;  
  193.         style.setBorderBottom(CellStyle.BORDER_THIN);  
  194.         //设置底边框颜色;  
  195.         style.setBottomBorderColor(HSSFColor.BLACK.index);  
  196.         //设置左边框;  
  197.         style.setBorderLeft(CellStyle.BORDER_THIN);  
  198.         //设置左边框颜色;  
  199.         style.setLeftBorderColor(HSSFColor.BLACK.index);  
  200.         //设置右边框;  
  201.         style.setBorderRight(CellStyle.BORDER_THIN);  
  202.         //设置右边框颜色;  
  203.         style.setRightBorderColor(HSSFColor.BLACK.index);  
  204.         //设置顶边框;  
  205.         style.setBorderTop(CellStyle.BORDER_THIN);  
  206.         //设置顶边框颜色;  
  207.         style.setTopBorderColor(HSSFColor.BLACK.index);  
  208.         //在样式用应用设置的字体;      
  209.         style.setFont(font);  
  210.         //设置自动换行;  
  211.         style.setWrapText(false);  
  212.         //设置水平对齐的样式为居中对齐;  
  213.         style.setAlignment(CellStyle.ALIGN_CENTER);  
  214.         //设置垂直对齐的样式为居中对齐;  
  215.         style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);  
  216.           
  217.         //设置背景填充色(前景色)  
  218.         style.setFillForegroundColor(HSSFColor.LIGHT_CORNFLOWER_BLUE.index);//设置别的颜色请去网上查询相关文档  
  219.         style.setFillPattern(CellStyle.SOLID_FOREGROUND);  
  220.         return style;  
  221.     }  
  222.       
  223.     public CellStyle getStyle(SXSSFWorkbook workbook,int fontSize) {  
  224.         //设置字体  
  225.         Font font = workbook.createFont();  
  226.         //设置字体大小  
  227.         font.setFontHeightInPoints((short)fontSize);  
  228.         //字体加粗    
  229.         //font.setBoldweight(Font.BOLDWEIGHT_BOLD);    
  230.         //设置字体名字     
  231.         font.setFontName("宋体");  
  232.         //设置样式;  
  233.         CellStyle style = workbook.createCellStyle();  
  234.         //设置底边框;  
  235.         style.setBorderBottom(CellStyle.BORDER_THIN);  
  236.         //设置底边框颜色;  
  237.         style.setBottomBorderColor(HSSFColor.BLACK.index);  
  238.         //设置左边框;       
  239.         style.setBorderLeft(CellStyle.BORDER_THIN);  
  240.         //设置左边框颜色;     
  241.         style.setLeftBorderColor(HSSFColor.BLACK.index);  
  242.         //设置右边框;     
  243.         style.setBorderRight(CellStyle.BORDER_THIN);  
  244.         //设置右边框颜色;     
  245.         style.setRightBorderColor(HSSFColor.BLACK.index);  
  246.         //设置顶边框;     
  247.         style.setBorderTop(CellStyle.BORDER_THIN);  
  248.         //设置顶边框颜色;      
  249.         style.setTopBorderColor(HSSFColor.BLACK.index);  
  250.         //在样式用应用设置的字体;  
  251.         style.setFont(font);  
  252.         //设置自动换行;     
  253.         style.setWrapText(false);  
  254.         //设置水平对齐的样式为居中对齐;  
  255.         style.setAlignment(CellStyle.ALIGN_CENTER);  
  256.         //设置垂直对齐的样式为居中对齐;  
  257.         style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);  
  258.            
  259.         return style;  
  260.     }  
  261. }  

猜你喜欢

转载自blog.csdn.net/qq_30270931/article/details/80115835