分享

使用 Excel 操作 poi

 scorpio365 2011-09-27

import java.io.FileInputStream;
import java.io.FileOutputStream;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

public class test1108 {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        test1108 test = new test1108();
        //test.read();
        test.write();
    }

    public void read() {
        try {
            //file read
            FileInputStream file = new FileInputStream("d://游戏数据库设计.xls");
            HSSFWorkbook book = new HSSFWorkbook(new POIFSFileSystem(file));
            HSSFSheet sheet = book.getSheetAt(0);//0页
            file.close();

            //页数
            int sheetNum = book.getNumberOfSheets();
            //行数
            int sheetRowNum = sheet.getLastRowNum();
            //指定行数对象
            HSSFRow row = sheet.getRow(0);
            //行数指定单元格对象
            HSSFCell cell = row.getCell((short) 0);
            //行数类型数字静态代表
            /*
             * 类型 HSSFCell.
             * CELL_TYPE_BLANK  空格 3
             * CELL_TYPE_BOOLEAN  布尔 4
             * CELL_TYPE_ERROR 错误类型 5
             * CELL_TYPE_FORMULA 公式 2
             * CELL_TYPE_NUMERIC 数字 0
             * CELL_TYPE_STRING 字符串 1
             * ENCODING_COMPRESSED_UNICODE 字符编码(默认为unicode)
             * ENCODING_UTF_16 设置cell编码解决中文高位字节截断 解决乱码
             */
            int cellTypeNum = cell.getCellType();
            //获得单元格内容
            String cellValue = cell.getStringCellValue();

            System.out.println("sheetNum:" + sheetNum);
            System.out.println("sheetRowNum:" + sheetRowNum);
            System.out.println("cellTypeNum:" + cellTypeNum);
            System.out.println("cellValue:" + cellValue);

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public void write() {
        try {
            //write
            HSSFWorkbook book = new HSSFWorkbook();
            HSSFSheet sheet = book.createSheet("god");
            
            
            /*数字*/
            //建立一行
            HSSFRow row = sheet.createRow(0);
            //建立一个单元格
            HSSFCell cell = row.createCell((short) 0);//建立位置
            //设置类型
            cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);//数字
            //设置值
            cell.setCellValue(0);
            
            /*浮点型*/
            //建立单元格样式
            HSSFCellStyle cellType = book.createCellStyle();
            //设置样式
            cellType.setDataFormat(HSSFDataFormat.getBuiltinFormat("0.00"));
            //建立一个单元格
            HSSFCell cell1 = row.createCell((short) 1);
            //设置单元格样式
            cell1.setCellStyle(cellType);//日期格式
            //字符编码
            cell1.setEncoding(HSSFCell.ENCODING_UTF_16);//解决乱码
            //设置值
            cell1.setCellValue("11.22");
            
            
            /*字符串*/
            //建立一个单元格
            HSSFCell cell2 = row.createCell((short) 2);
            //设置类型
            cell2.setCellType(HSSFCell.CELL_TYPE_STRING);//字符串
            //字符编码
            cell2.setEncoding(HSSFCell.ENCODING_UTF_16);//解决乱码
            //设置值
            cell2.setCellValue("哈哈");
            
            /*日期*/
            //建立单元格样式
            HSSFCellStyle cellType1 = book.createCellStyle();
            //设置样式
            cellType1.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy"));
            //建立一个单元格
            HSSFCell cell3 = row.createCell((short) 3);
            //设置单元格样式
            cell3.setCellStyle(cellType1);//日期格式
            //字符编码
            cell3.setEncoding(HSSFCell.ENCODING_UTF_16);//解决乱码
            //设置值
            cell3.setCellValue("2/31/2008");
            

            FileOutputStream out = new FileOutputStream("e://xx.xls");
            book.write(out);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}









import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Calendar;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

/**
 * @author caihua
 */
public class PoiExcelUtil {
   
//     设置cell编码解决中文高位字节截断
    private static short XLS_ENCODING = HSSFCell.ENCODING_UTF_16;

    // 定制浮点数格式
    private static String NUMBER_FORMAT = "#,##0.00";

    // 定制日期格式
    private static String DATE_FORMAT = "m/d/yy"; // "m/d/yy h:mm"
   
    private HSSFWorkbook wb = null;// book [includes sheet]

    private HSSFSheet sheet = null;

    private HSSFRow row = null;

    private int sheetNum = 0; // 第sheetnum个工作表

    private int rowNum = 0;

    private FileInputStream fis = null;

    private File file = null;

    private OutputStream out = null;

    private HSSFWorkbook workbook = null;

    public PoiExcelUtil() {
    }
   
    /*
     * 初始化 read
     */
    public void initRead(File file) {
        this.file = file;
    }
   
    /**
     * 初始化write
     *
     */
   
    public void initWrite(OutputStream out) {
        this.out = out;
        this.workbook = new HSSFWorkbook();
        this.sheet = workbook.createSheet();
    }
    public void setRowNum(int rowNum) {
        this.rowNum = rowNum;
    }

    public void setSheetNum(int sheetNum) {
        this.sheetNum = sheetNum;
    }

    public void setFile(File file) {
        this.file = file;
    }

    /**
     * 读取excel文件获得HSSFWorkbook对象
     */
    public void open() throws IOException {
        fis = new FileInputStream(file);
        wb = new HSSFWorkbook(new POIFSFileSystem(fis));
        fis.close();
    }

    /**
     * 返回sheet表数目
     *
     * @return int
     */
    public int getSheetCount() {
        int sheetCount = -1;
        sheetCount = wb.getNumberOfSheets();
        return sheetCount;
    }

    /**
     * sheetNum下的记录行数
     *
     * @return int
     */
    public int getRowCount() {
        if (wb == null)
            System.out.println("=============>WorkBook为空");
        HSSFSheet sheet = wb.getSheetAt(this.sheetNum);
        int rowCount = -1;
        rowCount = sheet.getLastRowNum();
        return rowCount;
    }

    /**
     * 读取指定sheetNum的rowCount
     *
     * @param sheetNum
     * @return int
     */
    public int getRowCount(int sheetNum) {
        HSSFSheet sheet = wb.getSheetAt(sheetNum);
        int rowCount = -1;
        rowCount = sheet.getLastRowNum();
        return rowCount;
    }

    /**
     * 得到指定行的内容
     *
     * @param lineNum
     * @return String[]
     */
    public String[] readExcelLine(int lineNum) {
        return readExcelLine(this.sheetNum, lineNum);
    }

    /**
     * 指定工作表和行数的内容
     *
     * @param sheetNum
     * @param lineNum
     * @return String[]
     */
    public String[] readExcelLine(int sheetNum, int lineNum) {
        if (sheetNum < 0 || lineNum < 0)
            return null;
        String[] strExcelLine = null;
        try {
            sheet = wb.getSheetAt(sheetNum);
            row = sheet.getRow(lineNum);

            int cellCount = row.getLastCellNum();
            strExcelLine = new String[cellCount + 1];
            for (int i = 0; i <= cellCount; i++) {
                strExcelLine[i] = readStringExcelCell(lineNum, i);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return strExcelLine;
    }

    /**
     * 读取指定列的内容
     *
     * @param cellNum
     * @return String
     */
    public String readStringExcelCell(int cellNum) {
        return readStringExcelCell(this.rowNum, cellNum);
    }

    /**
     * 指定行和列编号的内容
     *
     * @param rowNum
     * @param cellNum
     * @return String
     */
    public String readStringExcelCell(int rowNum, int cellNum) {
        return readStringExcelCell(this.sheetNum, rowNum, cellNum);
    }

    /**
     * 指定工作表、行、列下的内容
     *
     * @param sheetNum
     * @param rowNum
     * @param cellNum
     * @return String
     */
    public String readStringExcelCell(int sheetNum, int rowNum, int cellNum) {
        if (sheetNum < 0 || rowNum < 0)
            return "";
        String strExcelCell = "";
        try {
            sheet = wb.getSheetAt(sheetNum);
            row = sheet.getRow(rowNum);

            if (row.getCell((short) cellNum) != null) { // add this condition
                // judge
                switch (row.getCell((short) cellNum).getCellType()) {
                case HSSFCell.CELL_TYPE_FORMULA:
                    strExcelCell = "FORMULA ";
                    break;
                case HSSFCell.CELL_TYPE_NUMERIC: {
                    strExcelCell = String.valueOf(row.getCell((short) cellNum).getNumericCellValue());
                }
                    break;
                case HSSFCell.CELL_TYPE_STRING:
                    strExcelCell = row.getCell((short) cellNum).getStringCellValue();
                    break;
                case HSSFCell.CELL_TYPE_BLANK:
                    strExcelCell = "";
                    break;
                default:
                    strExcelCell = "";
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return strExcelCell;
    }

   

    /**
     * 导出Excel文件
     *
     * @throws Exception
     */
    public void export() throws Exception {
        try {
            workbook.write(out);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            throw new Exception(" 生成导出Excel文件出错! ", e);
        } catch (IOException e) {
            throw new Exception(" 写入Excel文件出错! ", e);
        }

    }

    /**
     * 增加一行
     *
     * @param index
     *            行号
     */
    public void createRow(int index) {
        this.row = this.sheet.createRow(index);
    }

    /**
     * 获取单元格的值
     *
     * @param index
     *            列号
     */
    public String getCell(int index) {
        HSSFCell cell = this.row.getCell((short) index);
        String strExcelCell = "";
        if (cell != null) { // add this condition
            // judge
            switch (cell.getCellType()) {
            case HSSFCell.CELL_TYPE_FORMULA:
                strExcelCell = "FORMULA ";
                break;
            case HSSFCell.CELL_TYPE_NUMERIC: {
                strExcelCell = String.valueOf(cell.getNumericCellValue());
            }
                break;
            case HSSFCell.CELL_TYPE_STRING:
                strExcelCell = cell.getStringCellValue();
                break;
            case HSSFCell.CELL_TYPE_BLANK:
                strExcelCell = "";
                break;
            default:
                strExcelCell = "";
                break;
            }
        }
        return strExcelCell;
    }

    /**
     * 设置单元格
     *
     * @param index
     *            列号
     * @param value
     *            单元格填充值
     */
    public void setCell(int index, int value) {
        HSSFCell cell = this.row.createCell((short) index);
        cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
        cell.setCellValue(value);
    }

    /**
     * 设置单元格
     *
     * @param index
     *            列号
     * @param value
     *            单元格填充值
     */
    public void setCell(int index, double value) {
        HSSFCell cell = this.row.createCell((short) index);
        cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
        cell.setCellValue(value);
        HSSFCellStyle cellStyle = workbook.createCellStyle(); // 建立新的cell样式
        HSSFDataFormat format = workbook.createDataFormat();
        cellStyle.setDataFormat(format.getFormat(NUMBER_FORMAT)); // 设置cell样式为定制的浮点数格式
        cell.setCellStyle(cellStyle); // 设置该cell浮点数的显示格式
    }

    /**
     * 设置单元格
     *
     * @param index
     *            列号
     * @param value
     *            单元格填充值
     */
    public void setCell(int index, String value) {
        HSSFCell cell = this.row.createCell((short) index);
        cell.setCellType(HSSFCell.CELL_TYPE_STRING);
        cell.setEncoding(XLS_ENCODING);
        cell.setCellValue(value);
    }

    /**
     * 设置单元格
     *
     * @param index
     *            列号
     * @param value
     *            单元格填充值
     */
    public void setCell(int index, Calendar value) {
        HSSFCell cell = this.row.createCell((short) index);
        cell.setEncoding(XLS_ENCODING);
        cell.setCellValue(value.getTime());
        HSSFCellStyle cellStyle = workbook.createCellStyle(); // 建立新的cell样式
        cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat(DATE_FORMAT)); // 设置cell样式为定制的日期格式
        cell.setCellStyle(cellStyle); // 设置该cell日期的显示格式
    }

    public static void main(String[] args) {
        System.out.println(" 开始导出Excel文件 ");

        File f = new File("C://qt.xls");
        PoiExcelUtil e = new PoiExcelUtil();

        try {
            e.initWrite(new FileOutputStream(f));
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        }

        e.createRow(0);
        e.setCell(0, "试题编码 ");
        e.setCell(1, "题型");
        e.setCell(2, "分值");
        e.setCell(3, "难度");
        e.setCell(4, "级别");
        e.setCell(5, "知识点");

        e.createRow(1);
        e.setCell(0, "t1");
        e.setCell(1, 1);
        e.setCell(2, 3.0);
        e.setCell(3, 1);
        e.setCell(4, "重要");
        e.setCell(5, "专业");

        try {
            e.export();
            System.out.println(" 导出Excel文件[成功] ");
        } catch (Exception ex) {
            System.out.println(" 导出Excel文件[失败] ");
            ex.printStackTrace();
        }

        File file = new File("d://新建 Microsoft Excel 工作表.xls");
        PoiExcelUtil readExcel = new PoiExcelUtil();
        try {
            readExcel.initRead(file);
            readExcel.open();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        readExcel.setSheetNum(1); // 设置读取索引为0的工作表
        // 总行数
        int count = readExcel.getRowCount();
        for (int i = 0; i <= count; i++) {
            String[] rows = readExcel.readExcelLine(i);
            for (int j = 0; j < rows.length; j++) {
                System.out.print(rows[j] + " ");
            }
            System.out.print("/n");
        }

    }
}




用apache POI 操作 Excel有几个关键的地方:

[1]读文件流
这个问题是一个IO问题

  1. InputStream in =  new  FileInputStream( "/tmp/aaa.xls" );  


[2]如何取得Excel的操作对象
这个也就相当于,Excel的工作区,在这个里面你可以取得当前excel文件的相关信息

  1. POIFSFileSystem poifs =  new  POIFSFileSystem(fis);   
  2. HSSFWorkbook wb =  new  HSSFWorkbook(poifs);  

HSSFWorkbook 对象,是我们最想得到的对象。
以后的所有操作都是从这里开始的。


[3]如何取得sheet的 数目

  1. wb.getNumberOfSheets()  


[4]如何根据index取得sheet对象

  1. HSSFSheet sheet = wb.getSheetAt( 0 );  

有了Sheet就相当于取得了一张表一样。


[5]如何取得有效的行数

  1. int  rowcount = sheet.getLastRowNum();  


[6]如何根据index取得行对象

  1. HSSFRow row = sheet.getRow(i);  
有了行对象,就可以取得每一个单元对象


[7]如何知道一个行有多少个单元
  1. colcount = row.getLastCellNum();  


[8]如何取得一个单元对象

  1. HSSFCell cell = row.getCell(j);  


[9]如何取得单元的值
此处仅以字符串为例

  1. if (cell!= null ){   
  2.        System.out.println( "cell is: " +cell.getStringCellValue());   
  3. }  

下面是我的测试的完整的程序。我也是从网上找的资料,然后自己又做了测试。在此又做了整理。
感谢网上提供此参考资料的朋友。

  1. package  demo.excel;   
  2.   
  3.   
  4. import  java.io.File;   
  5. import  java.io.FileInputStream;   
  6. import  java.io.FileNotFoundException;   
  7. import  java.io.IOException;   
  8. import  java.io.InputStream;   
  9. import  java.util.ArrayList;   
  10. import  java.util.List;   
  11.   
  12. import  org.apache.poi.hssf.eventusermodel.HSSFRequest;   
  13. import  org.apache.poi.hssf.model.Sheet;   
  14. import  org.apache.poi.hssf.model.Workbook;   
  15. import  org.apache.poi.hssf.usermodel.HSSFCell;   
  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. public   class  ExcelDemo {   
  22.   
  23.      public   static   void  main(String[] args) {   
  24.   
  25.         File f =  new  File( "/home/zhangyi/dell500.xls" );   
  26.   
  27.          if  (f.exists()) {   
  28.   
  29.              // read   
  30.              try  {   
  31.                 InputStream fis =  new  FileInputStream(f);   
  32.   
  33.                 POIFSFileSystem poifs =  new  POIFSFileSystem(fis);   
  34.                 HSSFWorkbook wb =  new  HSSFWorkbook(poifs);   
  35.   
  36.                 List retList =  new  ArrayList();   
  37.   
  38.                 System.out.println( "sheet number : "  + wb.getNumberOfSheets());   
  39.                    
  40.                    
  41.                 HSSFSheet s = wb.getSheetAt( 0 );   
  42.                 System.out.println( "sheet obj is : " +s);   
  43.                    
  44.                    
  45.                    
  46.                    
  47.                  for  ( int  h =  0 ; h < wb.getNumberOfSheets(); ++h) {   
  48.                     List list =  new  ArrayList();   
  49.   
  50.                     HSSFSheet sheet = wb.getSheetAt(h);   
  51.                      int  rowcount = sheet.getLastRowNum();   
  52.                     rowcount++;   
  53.                     System.out.print( "-----sheet["  + h +  "]: row count = "   
  54.                             + rowcount);   
  55.   
  56.                        
  57.                      int  colcount =  0 ;   
  58.                      for  ( int  i =  0 ; i < rowcount; ++i) {   
  59.                         HSSFRow row = sheet.getRow(i);  // i=0 indicate the first   
  60.                        
  61.                          // row   
  62.                          if  (row ==  null )   
  63.                              continue // without the row, break and continue;   
  64.                            
  65.                          if  (colcount ==  0 ) {  // colunm count set to column of   
  66.                              // the first effective row   
  67.                             colcount = row.getLastCellNum();   
  68.                             System.out.println( ", column count = "  + colcount);   
  69.                         }   
  70.   
  71.                         String[] fieldValue =  new  String[colcount];   
  72.                            
  73.                          for  ( short  j =  0 ; j < colcount; ++j) {  // column data in   
  74.                                                                  // the current   
  75.   
  76.                             HSSFCell cell = row.getCell(j);   
  77.                              // fieldValue[j] = getCellStringValue(cell);   
  78.                              if (cell!= null ){   
  79.                                 System.out.println( "cell is: " +cell.getStringCellValue());   
  80.                             }   
  81. //                            System.out.println("cell is : " +cell.getCellComment());   
  82.                                
  83.                         }   
  84.   
  85.                         list.add(fieldValue);   
  86.                     }   
  87.   
  88.                     retList.add(list);   
  89.                 }   
  90.   
  91.             }  catch  (FileNotFoundException e) {   
  92.                  // TODO Auto-generated catch block   
  93.                 e.printStackTrace();   
  94.             }  catch  (IOException e) {   
  95.                  // TODO Auto-generated catch block   
  96.                 e.printStackTrace();   
  97.             }   
  98.   
  99.         }   
  100.   
  101.     }   
  102.   
  103. }  

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多