Excel导入、导出

  1. package com.poi;  
  2.   
  3. import java.util.List;  
  4.   
  5. import org.apache.poi.hssf.usermodel.HSSFCellStyle;  
  6.   
  7. /** 
  8.  * <pre> 
  9.  *   Title: ExcelEntity.java 
  10.  *   Description:  
  11.  *   Copyright: Maple Copyright (c) 2013 
  12.  *   Company:  
  13.  * </pre> 
  14.  *  
  15.  * @author duanke 
  16.  * @version 1.0 
  17.  * @date 2013年12月31日 
  18.  */  
  19. public class ExcelEntity {  
  20.     private String sheetName; // excel 名称  
  21.   
  22.     private String[] columnNames; // 列名  
  23.   
  24.     private String[] propertyNames; // 属性名称  
  25.   
  26.     private String[] cLabels;  
  27.   
  28.     private int rpp = 200;  
  29.   
  30.     private HSSFCellStyle style = null;  
  31.   
  32.     @SuppressWarnings("rawtypes")  
  33.     private List resultList;  
  34.   
  35.     public String getSheetName() {  
  36.         return sheetName;  
  37.     }  
  38.   
  39.     public void setSheetName(String sheetName) {  
  40.         this.sheetName = sheetName;  
  41.     }  
  42.   
  43.     public String[] getColumnNames() {  
  44.         return columnNames;  
  45.     }  
  46.   
  47.     public void setColumnNames(String[] columnNames) {  
  48.         this.columnNames = columnNames;  
  49.     }  
  50.   
  51.     public String[] getPropertyNames() {  
  52.         return propertyNames;  
  53.     }  
  54.   
  55.     public void setPropertyNames(String[] propertyNames) {  
  56.         this.propertyNames = propertyNames;  
  57.     }  
  58.   
  59.     public String[] getCLabels() {  
  60.         return cLabels;  
  61.     }  
  62.   
  63.     public void setCLabels(String[] labels) {  
  64.         cLabels = labels;  
  65.     }  
  66.   
  67.     public int getRpp() {  
  68.         return rpp;  
  69.     }  
  70.   
  71.     public void setRpp(int rpp) {  
  72.         this.rpp = rpp;  
  73.     }  
  74.   
  75.     public HSSFCellStyle getStyle() {  
  76.         return style;  
  77.     }  
  78.   
  79.     public void setStyle(HSSFCellStyle style) {  
  80.         this.style = style;  
  81.     }  
  82.   
  83.     @SuppressWarnings("rawtypes")  
  84.     public List getResultList() {  
  85.         return resultList;  
  86.     }  
  87.   
  88.     @SuppressWarnings("rawtypes")  
  89.     public void setResultList(List resultList) {  
  90.         this.resultList = resultList;  
  91.     }  
  92. }  
[java]  view plain  copy
  1. package com.poi;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.OutputStream;  
  5. import java.io.UnsupportedEncodingException;  
  6. import java.text.SimpleDateFormat;  
  7. import java.util.Date;  
  8. import java.util.Iterator;  
  9. import java.util.List;  
  10. import java.util.Map;  
  11.   
  12. import javax.servlet.http.HttpServletResponse;  
  13.   
  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.Region;  
  22.   
  23. /** 
  24.  * <pre> 
  25.  *   Title: ExportExcelUtil.java 
  26.  *   Description:  
  27.  *   Copyright: Maple Copyright (c) 2013 
  28.  *   Company:  
  29.  * </pre> 
  30.  *  
  31.  * @author duanke 
  32.  * @version 1.0 
  33.  * @date 2013年12月31日 
  34.  */  
  35. public class ExportExcelUtil {  
  36.     /** 
  37.      * 创建Excel表格 
  38.      *  
  39.      * @param object 
  40.      * @param outStream 
  41.      * @throws Exception 
  42.      */  
  43.     @SuppressWarnings("rawtypes")  
  44.     public static void exportExcel(ExcelEntity object, OutputStream outStream) throws Exception {  
  45.         HSSFWorkbook wb = new HSSFWorkbook();  
  46.         HSSFSheet sheet = wb.createSheet(object.getSheetName());  
  47.         HSSFRow row = sheet.createRow(0);// 创建第一行  
  48.         HSSFCell cell = row.createCell(0);// 创建第一行的第一个单元格  
  49.         cell.setCellValue("序号");  
  50.         String[] colNames = object.getColumnNames();  
  51.         String[] propertys = object.getPropertyNames();  
  52.         for (int i = 0; i < colNames.length; i++) { // 添加列名,从第一行的第二个单元格开始添加  
  53.             row.createCell(i + 1).setCellValue(colNames[i]);  
  54.         }  
  55.         Iterator it = object.getResultList().iterator();  
  56.         int rowNum = 1// 从第二行开始添加数据  
  57.         while (it.hasNext()) {  
  58.             Map map = (Map) it.next();  
  59.             HSSFRow rw = sheet.createRow(rowNum);  
  60.             rw.createCell(0).setCellValue(rowNum); // 添加序号  
  61.             rowNum++;  
  62.             for (int x = 0; x < propertys.length; x++) {  
  63.                 String property = propertys[x];  
  64.                 if (map.containsKey(property)) {  
  65.                     Object value = map.get(propertys[x]); // 根据属性名称得到属性值  
  66.                     if (value == null || "null".equalsIgnoreCase(value.toString())) {  
  67.                         value = "";  
  68.                     }  
  69.                     rw.createCell(x + 1).setCellValue(value + "");  
  70.                 } else {  
  71.                     rw.createCell(x + 1).setCellValue("");  
  72.                 }  
  73.             }  
  74.         }  
  75.         try {  
  76.             wb.write(outStream);  
  77.             outStream.flush();  
  78.             outStream.close();  
  79.         } catch (IOException e) {  
  80.             if (outStream != null) {  
  81.                 outStream.close();  
  82.             }  
  83.             e.printStackTrace();  
  84.         }  
  85.     }  
  86.   
  87.     /** 
  88.      * 导出Excel 
  89.      *  
  90.      * @param response 
  91.      * @param list 
  92.      * @param columns 
  93.      * @param propertyNames 
  94.      * @throws IOException 
  95.      * @throws UnsupportedEncodingException 
  96.      * @throws Exception 
  97.      */  
  98.     @SuppressWarnings("rawtypes")  
  99.     public static void exportView(HttpServletResponse response, List<Map> list, String[] columns, String[] propertyNames) throws IOException, UnsupportedEncodingException, Exception {  
  100.         SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");  
  101.         ExcelEntity entity = new ExcelEntity();  
  102.         entity.setColumnNames(columns);  
  103.         entity.setPropertyNames(propertyNames);  
  104.         entity.setResultList(list);  
  105.         entity.setSheetName(sdf.format(new Date()));  
  106.   
  107.         OutputStream outStream = response.getOutputStream();  
  108.         response.setContentType("application/vnd.ms-excel;charset=UTF-8");  
  109.         String fileName = sdf.format(new Date()) + ".xls";  
  110.         response.setHeader("Content-Disposition""attachment;filename=" + new String(fileName.getBytes("GBK"), "iso8859-1"));  
  111.         exportExcel(entity, outStream);  
  112.     }  
  113.   
  114.     /** 
  115.      * 创建通用EXCEL头部 
  116.      *  
  117.      * @param headString 
  118.      *            头部显示的字符 
  119.      * @param colSum 
  120.      *            该报表的列数 
  121.      */  
  122.     @SuppressWarnings("deprecation")  
  123.     public void createNormalHead(String headString, int colSum, String sheetName) {  
  124.         HSSFWorkbook wb = new HSSFWorkbook();  
  125.         HSSFSheet sheet = wb.createSheet(sheetName);  
  126.         HSSFRow row = sheet.createRow(0);  
  127.   
  128.         // 设置第一行  
  129.         HSSFCell cell = row.createCell(0);  
  130.         row.setHeight((short400);  
  131.   
  132.         // 定义单元格为字符串类型  
  133.         cell.setCellType(HSSFCell.ENCODING_UTF_16);  
  134.         cell.setCellValue(new HSSFRichTextString(headString));  
  135.   
  136.         // 指定合并区域  
  137.         sheet.addMergedRegion(new Region(0, (short00, (short) colSum));  
  138.   
  139.         HSSFCellStyle cellStyle = wb.createCellStyle();  
  140.   
  141.         cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 指定单元格居中对齐  
  142.         cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 指定单元格垂直居中对齐  
  143.         cellStyle.setWrapText(true);// 指定单元格自动换行  
  144.   
  145.         // 设置单元格字体  
  146.         HSSFFont font = wb.createFont();  
  147.         font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);  
  148.         font.setFontName("宋体");  
  149.         font.setFontHeight((short300);  
  150.         cellStyle.setFont(font);  
  151.   
  152.         cell.setCellStyle(cellStyle);  
  153.     }  
  154. }  

[java]  view plain  copy
  1. package com.poi;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileInputStream;  
  5. import java.io.IOException;  
  6. import java.io.InputStream;  
  7. import java.util.ArrayList;  
  8. import java.util.HashMap;  
  9. import java.util.List;  
  10. import java.util.Map;  
  11.   
  12. import org.apache.commons.io.FilenameUtils;  
  13. import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
  14. import org.apache.poi.ss.usermodel.Cell;  
  15. import org.apache.poi.ss.usermodel.DateUtil;  
  16. import org.apache.poi.ss.usermodel.Row;  
  17. import org.apache.poi.ss.usermodel.Sheet;  
  18. import org.apache.poi.ss.usermodel.Workbook;  
  19. import org.apache.poi.ss.util.CellReference;  
  20. import org.apache.poi.xssf.usermodel.XSSFWorkbook;  
  21.   
  22. /** 
  23.  * <pre> 
  24.  *   Title: ReadExcel.java 
  25.  *   Description:  
  26.  *   Copyright: Maple Copyright (c) 2013 
  27.  *   Company:  
  28.  * </pre> 
  29.  *  
  30.  * @author duanke 
  31.  * @version 1.0 
  32.  * @date 2013年12月31日 
  33.  */  
  34. public class ReadExcel {  
  35.     /** 
  36.      * Excel 2003 
  37.      */  
  38.     private final static String XLS = "xls";  
  39.   
  40.     /** 
  41.      * Excel 2007 
  42.      */  
  43.     private final static String XLSX = "xlsx";  
  44.   
  45.     /** 
  46.      * 由Excel文件的Sheet导出至List 
  47.      *  
  48.      * @param file 
  49.      *            导入的excel文件 
  50.      * @param sheetNum 
  51.      *            excel工作空间,一般情况为0 
  52.      * @return 
  53.      */  
  54.     public static List<Map<String, Object>> exportListFromExcel(File file, int sheetNum) throws IOException {  
  55.         return exportListFromExcel(new FileInputStream(file), FilenameUtils.getExtension(file.getName()), sheetNum);  
  56.     }  
  57.   
  58.     /** 
  59.      * 由Excel流的Sheet导出至List 
  60.      *  
  61.      * @param is 
  62.      * @param extensionName 
  63.      * @param sheetNum 
  64.      * @return 
  65.      * @throws IOException 
  66.      */  
  67.     public static List<Map<String, Object>> exportListFromExcel(InputStream is, String extensionName, int sheetNum) throws IOException {  
  68.   
  69.         Workbook workbook = null;  
  70.   
  71.         if (extensionName.toLowerCase().equals(XLS)) {  
  72.             workbook = new HSSFWorkbook(is);  
  73.         } else if (extensionName.toLowerCase().equals(XLSX)) {  
  74.             workbook = new XSSFWorkbook(is);  
  75.         }  
  76.   
  77.         return readCell(workbook, sheetNum);  
  78.     }  
  79.   
  80.     /** 
  81.      * 读取Cell的值 
  82.      *  
  83.      * @param sheet 
  84.      * @return 
  85.      */  
  86.     public static List<Map<String, Object>> readCell(Workbook workbook, int sheetNum) {  
  87.         Sheet sheet = workbook.getSheetAt(sheetNum);  
  88.   
  89.         // 解析公式结果  
  90.         // FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();  
  91.   
  92.         List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();  
  93.         // 遍历所有行  
  94.         // for (Row row : sheet)  
  95.         // 除去表头即第一行  
  96.         for (int i = 1; i <= sheet.getLastRowNum(); i++) {  
  97.             Row row = sheet.getRow(i);  
  98.             Map<String, Object> map = new HashMap<String, Object>();  
  99.             // 便利所有列  
  100.             for (Cell cell : row) {  
  101.   
  102.                 // 获取单元格的类型  
  103.                 CellReference cellRef = new CellReference(row.getRowNum(), cell.getColumnIndex());  
  104.                 String key = cellRef.formatAsString();  
  105.   
  106.                 switch (cell.getCellType()) {  
  107.                 // 字符串  
  108.                 case Cell.CELL_TYPE_STRING:  
  109.                     map.put(key, cell.getRichStringCellValue().getString());  
  110.                     break;  
  111.                 // 数字  
  112.                 case Cell.CELL_TYPE_NUMERIC:  
  113.                     if (DateUtil.isCellDateFormatted(cell)) {  
  114.                         map.put(key, cell.getDateCellValue());  
  115.                     } else {  
  116.                         map.put(key, cell.getNumericCellValue());  
  117.                     }  
  118.                     break;  
  119.                 // boolean  
  120.                 case Cell.CELL_TYPE_BOOLEAN:  
  121.                     map.put(key, cell.getBooleanCellValue());  
  122.                     break;  
  123.                 // 方程式  
  124.                 case Cell.CELL_TYPE_FORMULA:  
  125.                     map.put(key, cell.getCellFormula());  
  126.                     break;  
  127.                 case Cell.CELL_TYPE_BLANK:  
  128.                     break;  
  129.                 case Cell.CELL_TYPE_ERROR:  
  130.                     break;  
  131.                 // 空值  
  132.                 default:  
  133.                     map.put(key, "");  
  134.                 }  
  135.             }  
  136.             list.add(map);  
  137.         }  
  138.         return list;  
  139.   
  140.     }  
  141.   
  142.     public static void main(String[] args) throws IOException {  
  143. //      String paths = "c:\\excel.xlsx";  
  144.         String paths = ReadExcel.class.getResource("c:\\excel.xlsx").getFile();  
  145.         List<Map<String, Object>> lists = ReadExcel.exportListFromExcel(new File(paths), 0);  
  146.         System.out.println(lists);  
  147.     }  
  148. }  

猜你喜欢

转载自blog.csdn.net/u013218587/article/details/77575228