使用poi讀寫excel文件


今天一個同學需要處理一個excel文件,於是我便在網上搜了一下方法,順便自己研究一下。剛剛參考網上資料,使用poi庫測試了一下讀取excel文件,效果不錯,跟大家分享一下。

要讀取的excel文件內容如下:

第一列是數值型,第二列是字符型,代碼如下:

package poi;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Iterator;

import org.apache.poi.hssf.extractor.ExcelExtractor;
import org.apache.poi.hssf.usermodel.HSSFCell;
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;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;

/**
 * 測試poi讀取excel文件內容
 * @author lihui
 *
 */
public class TestRead {

        /**
         * @param args
         */
        public static void main(String[] args){

                HSSFWorkbook wb = null;
                POIFSFileSystem fs = null;
                try {
                        //設置要讀取的文件路徑
                        fs = new POIFSFileSystem(new FileInputStream("d:\\book1.xls"));
                        //HSSFWorkbook相當於一個excel文件,HSSFWorkbook是解析excel2007之前的版本(xls)
                        //之后版本使用XSSFWorkbook(xlsx)
                        wb = new HSSFWorkbook(fs);
                        //獲得sheet工作簿
                        HSSFSheet sheet = wb.getSheetAt(0);
                        //獲得行
                        HSSFRow row = sheet.getRow(3);
                        //獲得行中的列,即單元格
                        HSSFCell cell = row.getCell(0);
                        //獲得單元格中的值,這里該單元格的值為數字,所以使用getNumericCellValue,如為字符串則會報錯
                        //如何取別的值,見print2方法
                        double msg = cell.getNumericCellValue();
                        System.out.println(msg);
                        print1();
                        print2();
                } catch (Exception e) {
                        e.printStackTrace();
                }
        }

        public static void print1() throws Exception {
                InputStream is = new FileInputStream("d:\\book1.xls");
                HSSFWorkbook wb = new HSSFWorkbook(new POIFSFileSystem(is));
                //A text extractor for Excel files.
                //Returns the textual content of the file, suitable for indexing by something like Lucene,
                //but not really intended for display to the user.
                //用來獲得整個excel文件的內容,表示為字符串
                ExcelExtractor extractor = new ExcelExtractor(wb);
                //字符串所包含的類型,詳見api
                extractor.setIncludeSheetNames(true);
                extractor.setFormulasNotResults(false);
                extractor.setIncludeCellComments(true);
                //獲得字符串形式
                String text = extractor.getText();
                System.out.println(text);
        }

        public static void print2() throws Exception {
                HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream(
                                "d:\\book1.xls"));
                HSSFSheet sheet = wb.getSheetAt(0);
                //迭代行
                for (Iterator<Row> iter = (Iterator<Row>) sheet.rowIterator(); iter
                                .hasNext();) {
                        Row row = iter.next();
                        //迭代列
                        for (Iterator<Cell> iter2 = (Iterator<Cell>) row.cellIterator(); iter2
                                        .hasNext();) {
                                Cell cell = iter2.next();
                                //用於測試的文件就2列,第一列為數字,第二列為字符串
                                //對於數字cell.getCellType的值為HSSFCell.CELL_TYPE_NUMERIC,為0
                                //對於字符串cell.getCellType的值為HSSFCell.CELL_TYPE_STRING,為1
                                //完整的類型列表請查看api
                                String content = cell.getCellType()==HSSFCell.CELL_TYPE_NUMERIC?cell.getNumericCellValue()+"":cell.getStringCellValue();
                                System.out.println(content);
                        }
                }
        }

}

 

 
        

下面是創建一個excel文件

 1 package poi;
 2 
 3 import java.io.FileOutputStream;
 4 import java.util.Date;
 5 
 6 import org.apache.poi.hssf.usermodel.HSSFCell;
 7 import org.apache.poi.hssf.usermodel.HSSFCellStyle;
 8 import org.apache.poi.hssf.usermodel.HSSFDataFormat;
 9 import org.apache.poi.hssf.usermodel.HSSFFont;
10 import org.apache.poi.hssf.usermodel.HSSFHyperlink;
11 import org.apache.poi.hssf.usermodel.HSSFRow;
12 import org.apache.poi.hssf.usermodel.HSSFSheet;
13 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
14 import org.apache.poi.hssf.util.CellRangeAddress;
15 import org.apache.poi.hssf.util.HSSFColor;
16 
17 public class TestWrite {
18 
19         /**
20          * @param args
21          */
22         public static void main(String[] args) throws Exception {
23                 // 創建Excel的工作書冊 Workbook,對應到一個excel文檔
24                 HSSFWorkbook wb = new HSSFWorkbook();
25 
26                 // 創建Excel的工作sheet,對應到一個excel文檔的tab
27                 HSSFSheet sheet = wb.createSheet("sheet1");
28 
29                 // 設置excel每列寬度
30                 sheet.setColumnWidth(0, 4000);
31                 sheet.setColumnWidth(1, 3500);
32 
33                 // 創建字體樣式
34                 HSSFFont font = wb.createFont();
35                 font.setFontName("Verdana");
36                 font.setBoldweight((short) 100);
37                 font.setFontHeight((short) 300);
38                 font.setColor(HSSFColor.BLUE.index);
39 
40                 // 創建單元格樣式
41                 HSSFCellStyle style = wb.createCellStyle();
42                 style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
43                 style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
44                 style.setFillForegroundColor(HSSFColor.LIGHT_TURQUOISE.index);
45                 style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
46 
47                 // 設置邊框
48                 style.setBottomBorderColor(HSSFColor.RED.index);
49                 style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
50                 style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
51                 style.setBorderRight(HSSFCellStyle.BORDER_THIN);
52                 style.setBorderTop(HSSFCellStyle.BORDER_THIN);
53 
54                 style.setFont(font);// 設置字體
55 
56                 // 創建Excel的sheet的一行
57                 HSSFRow row = sheet.createRow(0);
58                 row.setHeight((short) 500);// 設定行的高度
59                 // 創建一個Excel的單元格
60                 HSSFCell cell = row.createCell(0);
61 
62                 // 合並單元格(startRow,endRow,startColumn,endColumn)
63                 sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 2));
64 
65                 // 給Excel的單元格設置樣式和賦值
66                 cell.setCellStyle(style);
67                 cell.setCellValue("hello world");
68 
69                 // 設置單元格內容格式
70                 HSSFCellStyle style1 = wb.createCellStyle();
71                 style1.setDataFormat(HSSFDataFormat.getBuiltinFormat("h:mm:ss"));
72 
73                 style1.setWrapText(true);// 自動換行
74 
75                 row = sheet.createRow(1);
76 
77                 // 設置單元格的樣式格式
78 
79                 cell = row.createCell(0);
80                 cell.setCellStyle(style1);
81                 cell.setCellValue(new Date());
82 
83                 // 創建超鏈接
84                 HSSFHyperlink link = new HSSFHyperlink(HSSFHyperlink.LINK_URL);
85                 link.setAddress("http://www.baidu.com");
86                 cell = row.createCell(1);
87                 cell.setCellValue("百度");
88                 cell.setHyperlink(link);// 設定單元格的鏈接
89 
90                 FileOutputStream os = new FileOutputStream("e:\\workbook.xls");
91                 wb.write(os);
92                 os.close();
93 
94         }
95 
96 }

 


免責聲明!

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



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