HSSFWorkBooK用法(用於解析Excel文件)


來源於:http://blog.csdn.net/yahohi/article/details/7000537

1. jxl庫

jxl.jar庫下載地址:http://download.csdn.net/detail/yahohi/3826761

使用方法:

import java.io.FileInputStream;  
import java.io.InputStream;  
import jxl.Cell;  
import jxl.Sheet;  
import jxl.Workbook;  
  
public class xls {  
  
    public boolean readxlsByjxl(String filepath)  
    {  
        Workbook rwb;  
        try{  
            InputStream is = new FileInputStream(filepath);  
            rwb = Workbook.getWorkbook(is);  
            rwb.getNumberOfSheets();  
            Sheet st = rwb.getSheet("Sheet1");  
            int rows = st.getRows();  
            int cols = st.getColumns();  
            System.out.println("table name:"+st.getName());  
            System.out.println("total rows: "+rows);  
            System.out.println("total cols: "+cols);  
              
            for(int i = 0;i < rows;i ++)  
            {  
                Cell c1 = st.getCell(0, i);  
                Cell c2 = st.getCell(1, i);  
                Cell c3 = st.getCell(2, i);  
                Cell c4 = st.getCell(3, i);  
                  
                System.out.println(c1.getContents()+"  "+c2.getContents()+"   "+c3.getContents()+"  "+c4.getContents());  
            }  
        }  
        catch(Exception e)  
        {  
            e.printStackTrace();  
              
        }  
        return true;  
    }  
  
    public static void main(String[] args) {  
        // TODO Auto-generated method stub  
        xls x = new xls();  
        x.readxlsByjxl("C:/test.xls");  
          
    }  
  
}  

2. poi庫

poi.jar下載地址:http://download.csdn.net/detail/yahohi/3826817

poi.jar的詳細使用文檔:http://download.csdn.net/detail/yahohi/3826782

下面介紹和代碼引用自http://www.cnblogs.com/dcba1112/archive/2011/06/06/2073952.html

 

Poi 讀取文件的例子網上比較多, 但是很多都有小問題,今天我做了一個上傳文件並顯示XLS內容的模塊,

參考了http://www.iteye.com/topic/388005 例程 ,

由於我用的3.7 的版本, 例程里的代碼import 用的WorkbookFactory在3.7里已經不存在了,不知道

參考用的那個版本.所有我就使用了hssf和 ss相結合的調用.沒有再使用例程方生產方式

例程 Workbook wb = WorkbookFactory.create(is); 

我的代碼: HSSFWorkbook wb = new HSSFWorkbook(fs);

例程有個漏洞就是為判斷cell為空的情況,讀取的數據列會自動向前

移動一列.這個問題很驗證,我測試了一個下午才發現的.

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;

Java代碼
public class SummaryHSSF {
public static void main(String[] args) throws IOException {
//創建Workbook對象(這一個對象代表着對應的一個Excel文件)
//HSSFWorkbook表示以xls為后綴名的文件
Workbook wb = new HSSFWorkbook();
//獲得CreationHelper對象,這個應該是一個幫助類
CreationHelper helper = wb.getCreationHelper();
//創建Sheet並給名字(表示Excel的一個Sheet)
Sheet sheet1 = wb.createSheet("HSSF_Sheet_1");
Sheet sheet2 = wb.createSheet("HSSF_Sheet_2");
//Row表示一行Cell表示一列
Row row = null;
Cell cell = null;
for(int i=0;i<60;i=i+2){
//獲得這個sheet的第i行
row = sheet1.createRow(i);
//設置行長度自動
//row.setHeight((short)500);
row.setHeightInPoints(20);
//row.setZeroHeight(true);
for(int j=0;j<25;j++){
//設置每個sheet每一行的寬度,自動,根據需求自行確定
sheet1.autoSizeColumn(j+1, true);
//創建一個基本的樣式
CellStyle cellStyle = SummaryHSSF.createStyleCell(wb);
//獲得這一行的每j列
cell = row.createCell(j);
if(j==0){
//設置文字在單元格里面的位置
cellStyle = SummaryHSSF.setCellStyleAlignment(cellStyle, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER);
//先創建字體樣式,並把這個樣式加到單元格的字體里面
cellStyle.setFont(createFonts(wb));
//把這個樣式加到單元格里面
cell.setCellStyle(cellStyle);
//給單元格設值
cell.setCellValue(true);
}else if(j==1){
//設置文字在單元格里面的位置
cellStyle = SummaryHSSF.setCellStyleAlignment(cellStyle, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER);
//設置這個樣式的格式(Format)
cellStyle = SummaryHSSF.setCellFormat(helper,cellStyle, "#,##0.0000");
//先創建字體樣式,並把這個樣式加到單元格的字體里面
cellStyle.setFont(createFonts(wb));
//把這個樣式加到單元格里面
cell.setCellStyle(cellStyle);
//給單元格設值
cell.setCellValue(new Double(2008.2008));
}else if(j==2){
cellStyle = SummaryHSSF.setCellStyleAlignment(cellStyle, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER);
cellStyle.setFont(createFonts(wb));
cell.setCellStyle(cellStyle);
cell.setCellValue(helper.createRichTextString("RichString"+i+j));
}else if(j==3){
cellStyle = SummaryHSSF.setCellStyleAlignment(cellStyle, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER);
cellStyle = SummaryHSSF.setCellFormat(helper,cellStyle, "MM-yyyy-dd");
cell.setCellStyle(cellStyle);
cell.setCellValue(new Date());
}else if(j==24){
cellStyle = SummaryHSSF.setCellStyleAlignment(cellStyle, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER);
cellStyle.setFont(createFonts(wb));
//設置公式
cell.setCellFormula("SUM(E"+(i+1)+":X"+(i+1)+")");
}else{
cellStyle = SummaryHSSF.setCellStyleAlignment(cellStyle, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER);
cellStyle = SummaryHSSF.setFillBackgroundColors(cellStyle,IndexedColors.ORANGE.getIndex(),IndexedColors.ORANGE.getIndex(),CellStyle.SOLID_FOREGROUND);
cell.setCellStyle(cellStyle);
cell.setCellValue(1);
}
}
}
//輸出
OutputStream os = new FileOutputStream(new File("c://SummaryHSSF.xls"));
wb.write(os);
os.close();
}
/**
* 邊框
* @param wb
* @return
*/
public static CellStyle createStyleCell(Workbook wb){
CellStyle cellStyle = wb.createCellStyle();
//設置一個單元格邊框顏色
cellStyle.setBorderBottom(CellStyle.BORDER_THIN);
cellStyle.setBorderTop(CellStyle.BORDER_THIN);
cellStyle.setBorderLeft(CellStyle.BORDER_THIN);
cellStyle.setBorderRight(CellStyle.BORDER_THIN);
//設置一個單元格邊框顏色
cellStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());
cellStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());
cellStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());
cellStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());
return cellStyle;
}
/**
* 設置文字在單元格里面的位置
* CellStyle.ALIGN_CENTER
* CellStyle.VERTICAL_CENTER
* @param cellStyle
* @param halign
* @param valign
* @return
*/
public static CellStyle setCellStyleAlignment(CellStyle cellStyle,short halign,short valign){
//設置上下
cellStyle.setAlignment(CellStyle.ALIGN_CENTER);
//設置左右
cellStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
return cellStyle;
}
/**
* 格式化單元格
* 如#,##0.00,m/d/yy去HSSFDataFormat或XSSFDataFormat里面找
* @param cellStyle
* @param fmt
* @return
*/
public static CellStyle setCellFormat(CreationHelper helper,CellStyle cellStyle,String fmt){
//還可以用其它方法創建format
cellStyle.setDataFormat(helper.createDataFormat().getFormat(fmt));
return cellStyle;
}
/**
* 前景和背景填充的着色
* @param cellStyle
* @param bg IndexedColors.ORANGE.getIndex();
* @param fg IndexedColors.ORANGE.getIndex();
* @param fp CellStyle.SOLID_FOREGROUND
* @return
*/
public static CellStyle setFillBackgroundColors(CellStyle cellStyle,short bg,short fg,short fp){
//cellStyle.setFillBackgroundColor(bg);
cellStyle.setFillForegroundColor(fg);
cellStyle.setFillPattern(fp);
return cellStyle;
}
/**
* 設置字體
* @param wb
* @return
*/
public static Font createFonts(Workbook wb){
//創建Font對象
Font font = wb.createFont();
//設置字體
font.setFontName("黑體");
//着色
font.setColor(HSSFColor.BLUE.index);
//斜體
font.setItalic(true);
//字體大小
font.setFontHeight((short)300);
return font;
}
}

讀取Excel文件 

Java代碼
public class ReadExcel {
public static void main(String[] args) throws Exception {
InputStream is = new FileInputStream(new File("c://SummaryHSSF.xls"));
//根據輸入流創建Workbook對象
Workbook wb = WorkbookFactory.create(is);
//HSSFWorkbook wb = new HSSFWorkbook(is);
//get到Sheet對象
Sheet sheet = wb.getSheetAt(0);
//這個必須用接口
for(Row row : sheet){
for(Cell cell : row){ 
//實際讀取中這里需要判斷為空的情況
//if(cell == null){
//空處理
//}
//cell.getCellType是獲得cell里面保存的值的type
//如Cell.CELL_TYPE_STRING
switch(cell.getCellType()){
case Cell.CELL_TYPE_BOOLEAN:
//得到Boolean對象的方法
System.out.print(cell.getBooleanCellValue()+" ");
break;
case Cell.CELL_TYPE_NUMERIC:
//先看是否是日期格式
if(DateUtil.isCellDateFormatted(cell)){
//讀取日期格式
System.out.print(cell.getDateCellValue()+" ");
}else{
//讀取數字
System.out.print(cell.getNumericCellValue()+" ");
}
break;
case Cell.CELL_TYPE_FORMULA:
//讀取公式
System.out.print(cell.getCellFormula()+" ");
break;
case Cell.CELL_TYPE_STRING:
//讀取String
System.out.print(cell.getRichStringCellValue().toString()+" ");
break;
}
}
System.out.println("");
}
}
}

還有一種傳統的讀法 

Java代碼
Sheet sheet = wb.getSheetAt(0);
for (Iterator rit = sheet.rowIterator(); rit.hasNext(); ) {
Row row = (Row)rit.next();
for (Iterator cit = row.cellIterator(); cit.hasNext(); ) {
Cell cell = (Cell)cit.next();
// Do something here
}
}
HSSFSheet sheet = wb.getSheetAt(0);
for (Iterator<HSSFRow> rit = (Iterator<HSSFRow>)sheet.rowIterator(); rit.hasNext(); ) {
HSSFRow row = rit.next();
for (Iterator<HSSFCell> cit = (Iterator<HSSFCell>)row.cellIterator(); cit.hasNext(); ) {
HSSFCell cell = cit.next();
// Do something here
}
} 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM