封装对excel的操作,包括本地读写exce

来源:互联网 发布:mac如何剪切文件夹 编辑:程序博客网 时间:2024/06/05 08:14
  1. import java.io.File;   
  2. import java.io.FileInputStream;   
  3. import java.io.FileOutputStream;   
  4. import java.io.IOException;   
  5. import java.io.OutputStream;   
  6. import java.text.DecimalFormat;   
  7. import java.util.ArrayList;   
  8. import java.util.List;   
  9.   
  10. import javax.servlet.http.HttpServletResponse;   
  11.   
  12. import org.apache.poi.hssf.usermodel.HSSFCell;   
  13. import org.apache.poi.hssf.usermodel.HSSFRichTextString;   
  14. import org.apache.poi.hssf.usermodel.HSSFRow;   
  15. import org.apache.poi.hssf.usermodel.HSSFSheet;   
  16. import org.apache.poi.hssf.usermodel.HSSFWorkbook;   
  17. import org.apache.poi.poifs.filesystem.POIFSFileSystem;   
  18. import org.apache.poi.ss.usermodel.Cell;   
  19. import org.apache.poi.ss.usermodel.Row;   
  20. import org.apache.poi.ss.usermodel.Sheet;   
  21. import org.apache.poi.ss.usermodel.Workbook;   
  22. /**  
  23.  * 封装对excel的操作,包括本地读写excel和流中输出excel<br/>  
  24.  * 关联jar poi-3.5-beta5-20090219.jar<br/>  
  25.  * 有参构造函数参数为excel的全路径<br/>  
  26.  * @author 沙琪玛  
  27.  *  
  28.  */  
  29. public class ExcelUtils {   
  30.   
  31.     // excel文件路径   
  32.     private String path = "";   
  33.     /**  
  34.      * 无参构造函数 默认  
  35.      */  
  36.     public  ExcelUtils() {   
  37.   
  38.     }   
  39.     /**  
  40.      * 有参构造函数  
  41.      * @param path excel路径  
  42.      */  
  43.     public  ExcelUtils(String path) {   
  44.         this.path = path;   
  45.     }   
  46.     /**  
  47.      * 在磁盘生成一个含有内容的excel,路径为path属性  
  48.      * @param sheetName 导出的sheet名称  
  49.      * @param fieldName 列名数组  
  50.      * @param data 数据组  
  51.      * @throws IOException   
  52.      */  
  53.     public void makeExcel(String sheetName,String[] fieldName,List<String[]> data) throws IOException {   
  54.         //在内存中生成工作薄   
  55.         HSSFWorkbook workbook = makeWorkBook(sheetName,fieldName,data);   
  56.         //截取文件夹路径   
  57.         String filePath=path.substring(0,path.lastIndexOf("//"));   
  58.         // 如果路径不存在,创建路径   
  59.         File file = new File(filePath);   
  60.         //System.out.println(path+"-----------"+file.exists());   
  61.         if (!file.exists())   
  62.             file.mkdirs();   
  63.         FileOutputStream fileOut = new FileOutputStream(path);   
  64.         workbook.write(fileOut);   
  65.         fileOut.close();   
  66.     }   
  67.     /**  
  68.      * 在输出流中导出excel  
  69.      * @param excelName 导出的excel名称 包括扩展名  
  70.      * @param sheetName 导出的sheet名称  
  71.      * @param fieldName 列名数组  
  72.      * @param data 数据组  
  73.      * @param response response  
  74.      */  
  75.     public void makeStreamExcel(String excelName, String sheetName,String[] fieldName   
  76.             , List<String[]> data,HttpServletResponse response) {   
  77.          OutputStream os = null;   
  78.          try {   
  79.             response.reset(); // 清空输出流   
  80.             os = response.getOutputStream(); // 取得输出流   
  81.             response.setHeader("Content-disposition""attachment; filename="  
  82.                     + new String(excelName.getBytes(), "ISO-8859-1")); // 设定输出文件头   
  83.             response.setContentType("application/msexcel"); // 定义输出类型   
  84.         } catch (IOException ex) {// 捕捉异常   
  85.             System.out.println("流操作错误:" + ex.getMessage());   
  86.         }   
  87.         //在内存中生成工作薄   
  88.         HSSFWorkbook workbook = makeWorkBook(sheetName,fieldName,data);   
  89.         try {   
  90.             os.flush();   
  91.             workbook.write(os);   
  92.         } catch (IOException e) {   
  93.             e.printStackTrace();   
  94.             System.out.println("Output is closed");   
  95.         }   
  96.     }   
  97.     /**  
  98.      * 根据条件,生成工作薄对象到内存  
  99.      * @param sheetName 工作表对象名称  
  100.      * @param fieldName 首列列名称  
  101.      * @param data 数据  
  102.      * @return HSSFWorkbook  
  103.      */  
  104.     private HSSFWorkbook makeWorkBook(String sheetName,String[] fieldName   
  105.             , List<String[]> data)   
  106.     {   
  107.         // 产生工作薄对象   
  108.         HSSFWorkbook workbook = new HSSFWorkbook();   
  109.         // 产生工作表对象   
  110.         HSSFSheet sheet = workbook.createSheet();   
  111.         // 为了工作表能支持中文,设置字符集为UTF_16   
  112.         workbook.setSheetName(0, sheetName);   
  113.         // 产生一行   
  114.         HSSFRow row = sheet.createRow(0);   
  115.         // 产生单元格   
  116.         HSSFCell cell;   
  117.         // 写入各个字段的名称   
  118.         for (int i = 0; i < fieldName.length; i++) {   
  119.             // 创建第一行各个字段名称的单元格   
  120.             cell = row.createCell((short) i);   
  121.             // 设置单元格内容为字符串型   
  122.             cell.setCellType(HSSFCell.CELL_TYPE_STRING);   
  123.             // 为了能在单元格中输入中文,设置字符集为UTF_16   
  124.             // cell.setEncoding(HSSFCell.ENCODING_UTF_16);   
  125.             // 给单元格内容赋值   
  126.             cell.setCellValue(new HSSFRichTextString(fieldName[i]));   
  127.         }   
  128.         // 写入各条记录,每条记录对应excel表中的一行   
  129.         for (int i = 0; i < data.size(); i++) {   
  130.             String[] tmp = data.get(i);   
  131.             // 生成一行   
  132.             row = sheet.createRow(i + 1);   
  133.             for (int j = 0; j < tmp.length; j++) {   
  134.                 cell = row.createCell((short) j);   
  135.                 //设置单元格字符类型为String   
  136.                 cell.setCellType(HSSFCell.CELL_TYPE_STRING);   
  137.                 cell.setCellValue(new HSSFRichTextString((tmp[j] == null) ? "" : tmp[j]));   
  138.             }   
  139.         }   
  140.         return workbook;   
  141.     }   
  142.   
  143.     public void write(int sheetOrder,int colum, int row, String content) throws Exception {   
  144.         Workbook workbook = new HSSFWorkbook(new POIFSFileSystem(   
  145.                 new FileInputStream(path)));   
  146.         Sheet sheet = workbook.getSheetAt(sheetOrder);   
  147.         Row rows = sheet.createRow(row);   
  148.         Cell cell = rows.createCell(colum);   
  149.         cell.setCellValue(content);   
  150.         FileOutputStream fileOut = new FileOutputStream(path);   
  151.         workbook.write(fileOut);   
  152.         fileOut.close();   
  153.   
  154.     }   
  155.     /**  
  156.      * 得到一个工作区最后一条记录的序号  
  157.      * @param sheetOrder 工作区序号  
  158.      * @return int  
  159.      * @throws IOException  
  160.      */  
  161.     public int getSheetLastRowNum(int sheetOrder) throws IOException   
  162.     {   
  163.         Workbook workbook = new HSSFWorkbook(new POIFSFileSystem(   
  164.                 new FileInputStream(path)));   
  165.         Sheet sheet = workbook.getSheetAt(sheetOrder);   
  166.         return sheet.getLastRowNum();   
  167.     }   
  168.     public String read(int sheetOrder,int colum, int row) throws Exception {   
  169.         Workbook workbook = new HSSFWorkbook(new POIFSFileSystem(   
  170.                 new FileInputStream(path)));   
  171.         Sheet sheet = workbook.getSheetAt(sheetOrder);   
  172.         Row rows = sheet.getRow(row);   
  173.         Cell cell = rows.getCell(colum);   
  174.         String content = cell.getStringCellValue();   
  175.         return content;   
  176.     }   
  177.     /**  
  178.      * 根据path属性,在磁盘生成一个新的excel  
  179.      * @throws IOException  
  180.      */  
  181.     public void makeEmptyExcel() throws IOException {   
  182.         Workbook wb = new HSSFWorkbook();   
  183.         Sheet sheet = wb.createSheet("new sheet");   
  184.         //截取文件夹路径   
  185.         String filePath=path.substring(0,path.lastIndexOf("//"));   
  186.         // 如果路径不存在,创建路径   
  187.         File file = new File(filePath);   
  188.         if (!file.exists())   
  189.             file.mkdirs();   
  190.         FileOutputStream fileOut = new FileOutputStream(filePath + "//" + path.substring(path.lastIndexOf("//")+1));   
  191.         wb.write(fileOut);   
  192.         fileOut.close();   
  193.     }   
  194.     /**  
  195.      * 根据工作区序号,读取该工作去下的所有记录,每一条记录是一个String[]<br/>  
  196.      * 注意如果单元格中的数据为数字将会被自动转换为字符串<br/>  
  197.      * 如果单元格中存在除数字,字符串以外的其他类型数据,将会产生错误  
  198.      * @param sheetOrder 工作区序号  
  199.      * @return  
  200.      * @throws IOException   
  201.      * @throws    
  202.      */  
  203.     public List<String[]> getDataFromSheet(int sheetOrder) throws IOException   
  204.     {   
  205.         Workbook workbook = new HSSFWorkbook(new POIFSFileSystem(   
  206.                 new FileInputStream(path)));   
  207.         Sheet sheet = workbook.getSheetAt(sheetOrder);   
  208.         List<String[]> strs=new ArrayList<String[]>();   
  209.         //注意得到的行数是基于0的索引 遍历所有的行   
  210.         //System.out.println(sheet.getLastRowNum());   
  211.         for(int i=0 ; i<=sheet.getLastRowNum() ; i++){   
  212.             Row rows = sheet.getRow(i);   
  213.             String[] str =new String[rows.getLastCellNum()];   
  214.             //遍历每一列   
  215.             for (int k = 0; k < rows.getLastCellNum(); k++) {   
  216.                 Cell cell = rows.getCell(k);   
  217.                 //数字类型时   
  218.                 if(0==cell.getCellType()){   
  219.                     //用于格式化数字,只保留数字的整数部分   
  220.                     DecimalFormat df=new DecimalFormat("########");      
  221.                     str[k]=df.format(cell.getNumericCellValue());   
  222.                 }   
  223.                 else  
  224.                     str[k] =cell.getStringCellValue();   
  225.                 //System.out.println(cell.getCellType()+"-------------"+str[k]);   
  226.             }   
  227.             strs.add(str);   
  228.         }   
  229.         return strs ;   
  230.     }   
  231.     //   public static void main(String[] args) throws Exception {   
  232.     //   ExcelUtils eu=new ExcelUtils("D://Tomcat 5.5//webapps//sms//UserFiles//log//2009-11-16 16:47:20 导入手机号码日志.xls");   
  233.     //   List<String[]> ss=new ArrayList<String[]>();   
  234.     //   ss.add(new String[]{"你撒地方","sdfds"});   
  235.     //   ss.add(new String[]{"瓦尔","撒地方"});   
  236.     //   eu.makeExcel("smsLog", new String[]{"色粉","的是否"}, ss);   
  237.     // List<String[]> strs=excelUtils.getDataFromSheet(0);   
  238.     // for (String[] str : strs) {   
  239.     // for (String s : str) {   
  240.     // System.out.println(s);   
  241.     // }   
  242.     // }   
  243.     // String content = "Hello Worlds";   
  244.     // excelUtils.write(2, 3, content);   
  245.     // String newContent = excelUtils.read(0,1, 1);   
  246.     // System.out.println(newContent);   
  247.     // excelUtils.makeEmptyExcel("d://a//ab", "a.xls");   
  248.     //  }   
  249. }  
原创粉丝点击