使用JAVA读取和写入EXCEL文件

来源:互联网 发布:cocos js 编辑:程序博客网 时间:2024/05/24 15:38

下载地址http://download.csdn.net/detail/u010634066/8302683  下载直接用


首先要下载 poi包和jxl包


读取部分:

[java] view plain copy
  1. import java.io.BufferedInputStream;  
  2. import java.io.File;  
  3. import java.io.FileInputStream;  
  4. import java.io.FileNotFoundException;  
  5. import java.io.IOException;  
  6.   
  7. import java.text.DecimalFormat;  
  8. import java.text.SimpleDateFormat;  
  9. import java.util.ArrayList;  
  10. import java.util.Arrays;  
  11. import java.util.Date;  
  12. import java.util.List;  
  13.   
  14. import org.apache.poi.hssf.usermodel.HSSFCell;  
  15. import org.apache.poi.hssf.usermodel.HSSFDateUtil;  
  16. import org.apache.poi.hssf.usermodel.HSSFRow;  
  17. import org.apache.poi.hssf.usermodel.HSSFSheet;  
  18. import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
  19. import org.apache.poi.poifs.filesystem.POIFSFileSystem;  
  20.   
  21.   
  22. /**============================================================ 
  23.  * 版权:  
  24.  * 包:  
  25.  * 修改记录: 
  26.  * 日期                               作者                               内容 
  27.  * ============================================================= 
  28.  * 2014-12-25       shirenchuang         
  29.  * ============================================================*/  
  30.   
  31. /** 
  32.  * @author shirenchuang 
  33.  * 
  34.  */  
  35. public class ReadExecl {  
  36.   
  37.     /*private String fileUrl; 
  38.     
  39.     public ReadExecl(String fileUrl) { 
  40.         // TODO Auto-generated constructor stub 
  41.         this.fileUrl = fileUrl; 
  42.     }*/  
  43.    // File file = new File(fileUrl);  
  44.       
  45.     /** 
  46.  
  47.      * 读取Excel的内容,第一维数组存储的是一行中格列的值,二维数组存储的是多少个行 
  48.  
  49.      * @param file 读取数据的源Excel 
  50.  
  51.      * @param ignoreRows 读取数据忽略的行数,比喻行头不需要读入 忽略的行数为1 
  52.  
  53.      * @return 读出的Excel中数据的内容 
  54.  
  55.      * @throws FileNotFoundException 
  56.  
  57.      * @throws IOException 
  58.  
  59.      */  
  60.       
  61.     public static List<String[][]> getData(File file,int ignoreRows) throws IOException{  
  62.         //返回所有工作表的数据  
  63.         List<String[][]> result = new ArrayList<String[][]>();  
  64.         BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));  
  65.         POIFSFileSystem  fs = new POIFSFileSystem(in);  
  66.         HSSFWorkbook wb = new HSSFWorkbook(fs);  
  67.         HSSFCell cell = null;  
  68.         wb.getNumberOfSheets();  
  69.         //多个工作表  
  70.         for(int i=0;i<wb.getNumberOfSheets();i++){  
  71.             //得到工作表  
  72.             HSSFSheet hf = wb.getSheetAt(i);  
  73.             //一个工作表的数据   挤得加上1  比如execl加上第一行的列名 总共66  但是getLastRowNum()是65 把列明也算上  
  74.             String[][] rowResult = new String[hf.getLastRowNum()+1][7];  
  75.             //每个工作表的多行  
  76.             for(int rownumber = ignoreRows; rownumber<=hf.getLastRowNum();rownumber++){  
  77.                   
  78.                   
  79.                 //得到的row的行数不确定的   如果那一行后面有空格  有可能会忽略空格列  
  80.                 HSSFRow row = hf.getRow(rownumber);  
  81.                 if (row == null) {  
  82.                     continue;  
  83.                 }  
  84.                 //一行的数据  
  85.                 String[] colResult = new String[row.getLastCellNum()];  
  86.                 //得到一行的多个列  
  87.                 /** 
  88.                  * 这里有个问题  就是row.getLastCellNum()有个情况得到的不准确   
  89.                  * 例子:EXECL总共7列数据   但是实际上最后几列有的为空,它会默认把空的列不计入列值; 
  90.                  * 导致的错误就是你调用写入方法的时候会有用的列值  会出错; 
  91.                  *  
  92.                  */  
  93.                 for(short colnumber = 0;colnumber<row.getLastCellNum();colnumber++){  
  94.                         String value="";  
  95.                     cell=row.getCell(colnumber);  
  96.                     //将cell装换类型  
  97.                     if(cell!=null){  
  98.                         cell.setEncoding(HSSFCell.ENCODING_UTF_16);  
  99.                         switch(cell.getCellType()){  
  100.                         case HSSFCell.CELL_TYPE_STRING:  
  101.                             value = cell.getStringCellValue();  
  102.                             break;  
  103.                         case HSSFCell.CELL_TYPE_NUMERIC:  
  104.                             if (HSSFDateUtil.isCellDateFormatted(cell)) {  
  105.   
  106.                                 Date date = cell.getDateCellValue();  
  107.   
  108.                                 if (date != null) {  
  109.   
  110.                                     value = new SimpleDateFormat("yyyy-MM-dd")  
  111.   
  112.                                            .format(date);  
  113.   
  114.                                 } else {  
  115.   
  116.                                     value = "";  
  117.   
  118.                                 }  
  119.   
  120.                              } else {  
  121.   
  122.                                 value = new DecimalFormat("0").format(cell  
  123.   
  124.                                        .getNumericCellValue());  
  125.   
  126.                              }  
  127.   
  128.                              break;  
  129.                         case HSSFCell.CELL_TYPE_FORMULA:  
  130.                          // 导入时如果为公式生成的数据则无值  
  131.   
  132.                             if (!cell.getStringCellValue().equals("")) {  
  133.   
  134.                                value = cell.getStringCellValue();  
  135.   
  136.                             } else {  
  137.   
  138.                                value = cell.getNumericCellValue() + "";  
  139.   
  140.                             }  
  141.   
  142.                             break;  
  143.                         
  144.                         case HSSFCell.CELL_TYPE_BLANK:  
  145.   
  146.                             break;  
  147.   
  148.                         case HSSFCell.CELL_TYPE_ERROR:  
  149.   
  150.                             value = "";  
  151.   
  152.                             break;  
  153.   
  154.                         case HSSFCell.CELL_TYPE_BOOLEAN:  
  155.   
  156.                             value = (cell.getBooleanCellValue() == true ? "Y"  
  157.   
  158.                                    : "N");  
  159.   
  160.                             break;  
  161.   
  162.                         default:  
  163.   
  164.                             value = "";  
  165.                         }//switch  
  166.                           
  167.                     }//if  
  168.                     if (colnumber == 0 && value.trim().equals("")) {  
  169.                        // break;  
  170.                      }  
  171.                       
  172.                     colResult[colnumber]=rightTrim(value);  
  173.                 }//for()列  
  174.                 rowResult[rownumber]=colResult;  
  175.             }//for() 行  
  176.             if(rowResult!=null)  
  177.             result.add(rowResult);  
  178.         }//for工作表  
  179.         in.close();  
  180.           
  181.         return result;  
  182.     }  
  183.       
  184.       
  185.     /** 
  186.  
  187.      * 去掉字符串右边的空格 
  188.  
  189.      * @param str 要处理的字符串 
  190.  
  191.      * @return 处理后的字符串 
  192.  
  193.      */  
  194.   
  195.      public static String rightTrim(String str) {  
  196.   
  197.        if (str == null) {  
  198.   
  199.            return "";  
  200.   
  201.        }  
  202.   
  203.        int length = str.length();  
  204.   
  205.        for (int i = length - 1; i >= 0; i--) {  
  206.   
  207.            if (str.charAt(i) != 0x20) {  
  208.   
  209.               break;  
  210.   
  211.            }  
  212.   
  213.            length--;  
  214.   
  215.        }  
  216.   
  217.        return str.substring(0, length);  
  218.   
  219.     }  
  220.       
  221. }  

写入部分

[java] view plain copy
  1. import java.io.File;  
  2. import java.io.IOException;  
  3.   
  4. import jxl.Workbook;  
  5. import jxl.write.Label;  
  6. import jxl.write.WritableSheet;  
  7. import jxl.write.WritableWorkbook;  
  8. import jxl.write.WriteException;  
  9.   
  10.   
  11.   
  12. /**============================================================ 
  13.  * 版权: 元亨通信 版权所有 (c) 2002 - 2012 
  14.  * 包:  
  15.  * 修改记录: 
  16.  * 日期                               作者                               内容 
  17.  * ============================================================= 
  18.  * 2014-12-25       shirenchuang         
  19.  * ============================================================*/  
  20.   
  21. /** 
  22.  * @author shirenchuang 
  23.  * 
  24.  */  
  25. public class WriterExecl {  
  26.     private static String writeUrl ="";  
  27.     public String getWriteUrl() {  
  28.         return writeUrl;  
  29.     }  
  30.   
  31.   
  32.     public void setWriteUrl(String writeUrl) {  
  33.         this.writeUrl = writeUrl;  
  34.     }  
  35.   
  36.   
  37.     public WriterExecl(String writeUrl ) {  
  38.         // TODO Auto-generated constructor stub  
  39.         this.writeUrl= writeUrl;  
  40.     }  
  41.       
  42.       
  43.     /**  
  44.      *   
  45.      * 这是单纯的写EXCEL表格  
  46.      * **/    
  47.     public static void writeEx(int row,String[][] data){    
  48.           
  49.         WritableWorkbook wwb = null;       
  50.         Label label = null;       
  51.         String file =writeUrl;    
  52.         try {       
  53.             // 创建可写入的工作簿对象       
  54.              
  55.             wwb = Workbook.createWorkbook(new File(file));       
  56.             if (wwb != null) {       
  57.                 // 在工作簿里创建可写入的工作表,第一个参数为工作表名,第二个参数为该工作表的所在位置     
  58.                 WritableSheet ws = wwb.createSheet("test"0);       
  59.                 if (ws != null) {       
  60.                     /* 添加表结构 */      
  61.                     // 行       
  62.                     for (int i=0;i<row;i++) {       
  63.                         // 列       
  64.                         for (int j=0;j<data[i].length;j++) {       
  65.                             // Label构造器中有三个参数,第一个为列,第二个为行,第三个则为单元格填充的内容    
  66.                               
  67.                             label = new Label(j, i,data[i][j] );       
  68.                             // 将被写入数据的单元格添加到工作表       
  69.                             ws.addCell(label);       
  70.                         }       
  71.                     }       
  72.                     // 从内存中写入到文件       
  73.                     wwb.write();       
  74.                 }       
  75.                 System.out.println("路径为:" + file + "的工作簿写入数据成功!");       
  76.             }       
  77.         } catch (Exception e) {       
  78.             System.out.println(e.getMessage());       
  79.         } finally {       
  80.             try {     
  81.                 wwb.close();    
  82.             } catch (WriteException e) {    
  83.                 // TODO Auto-generated catch block    
  84.                 e.printStackTrace();    
  85.             } catch (IOException e) {    
  86.                 // TODO Auto-generated catch block    
  87.                 e.printStackTrace();    
  88.             }       
  89.         }       
  90.     }    
  91. }  

主方法:


[java] view plain copy
  1. import java.io.File;  
  2. import java.io.IOException;  
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5.   
  6.   
  7.   
  8.   
  9. public class main {  
  10.   
  11.     public static void main(String[] args) throws IOException{  
  12.         ReadExecl re = new ReadExecl();  
  13.         File file = new File("C:/Users/Administrator/Desktop/test.xls");  
  14.         WriterExecl we = new WriterExecl("C:/Users/Administrator/Desktop/衢州用户表.xls");  
  15.         List<String[][]> result = new ArrayList<String[][]>();  
  16.         //不忽略行 从0开始  
  17.         result =  re.getData(file, 0);  
  18.         //有多少行  
  19.         int row = result.get(0).length;  
  20.   
  21.          //写入  传入参数row   不传column  column是不确定的  
  22.         we.writeEx(row,result.get(0));  
  23.          
  24.     }  
  25. }  
0 0
原创粉丝点击