使用poi读写excel文件

使用poi库测试了一下读取excel文件,效果不错,跟大家分享一下。

第一列是数值型,第二列是字符型,代码如下:

 1 package poi;
 2 
 3 import java.io.FileInputStream;
 4 import java.io.InputStream;
 5 import java.util.Iterator;
 6 
 7 import org.apache.poi.hssf.extractor.ExcelExtractor;
 8 import org.apache.poi.hssf.usermodel.HSSFCell;
 9 import org.apache.poi.hssf.usermodel.HSSFRow;
10 import org.apache.poi.hssf.usermodel.HSSFSheet;
11 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
12 import org.apache.poi.poifs.filesystem.POIFSFileSystem;
13 import org.apache.poi.ss.usermodel.Cell;
14 import org.apache.poi.ss.usermodel.Row;
15 
16 /**
17  * 测试poi读取excel文件内容
18  * @author lihui
19  *
20  */
21 public class TestRead {
22 
23         /**
24          * @param args
25          */
26         public static void main(String[] args){
27 
28                 HSSFWorkbook wb = null;
29                 POIFSFileSystem fs = null;
30                 try {
31                         //设置要读取的文件路径
32                         fs = new POIFSFileSystem(new FileInputStream("d:\book1.xls"));
33                         //HSSFWorkbook相当于一个excel文件,HSSFWorkbook是解析excel2007之前的版本(xls)
34                         //之后版本使用XSSFWorkbook(xlsx)
35                         wb = new HSSFWorkbook(fs);
36                         //获得sheet工作簿
37                         HSSFSheet sheet = wb.getSheetAt(0);
38                         //获得行
39                         HSSFRow row = sheet.getRow(3);
40                         //获得行中的列,即单元格
41                         HSSFCell cell = row.getCell(0);
42                         //获得单元格中的值,这里该单元格的值为数字,所以使用getNumericCellValue,如为字符串则会报错
43                         //如何取别的值,见print2方法
44                         double msg = cell.getNumericCellValue();
45                         System.out.println(msg);
46                         print1();
47                         print2();
48                 } catch (Exception e) {
49                         e.printStackTrace();
50                 }
51         }
52 
53         public static void print1() throws Exception {
54                 InputStream is = new FileInputStream("d:\book1.xls");
55                 HSSFWorkbook wb = new HSSFWorkbook(new POIFSFileSystem(is));
56                 //A text extractor for Excel files.
57                 //Returns the textual content of the file, suitable for indexing by something like Lucene,
58                 //but not really intended for display to the user.
59                 //用来获得整个excel文件的内容,表示为字符串
60                 ExcelExtractor extractor = new ExcelExtractor(wb);
61                 //字符串所包含的类型,详见api
62                 extractor.setIncludeSheetNames(true);
63                 extractor.setFormulasNotResults(false);
64                 extractor.setIncludeCellComments(true);
65                 //获得字符串形式
66                 String text = extractor.getText();
67                 System.out.println(text);
68         }
69 
70         public static void print2() throws Exception {
71                 HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream(
72                                 "d:\book1.xls"));
73                 HSSFSheet sheet = wb.getSheetAt(0);
74                 //迭代行
75                 for (Iterator<Row> iter = (Iterator<Row>) sheet.rowIterator(); iter
76                                 .hasNext();) {
77                         Row row = iter.next();
78                         //迭代列
79                         for (Iterator<Cell> iter2 = (Iterator<Cell>) row.cellIterator(); iter2
80                                         .hasNext();) {
81                                 Cell cell = iter2.next();
82                                 //用于测试的文件就2列,第一列为数字,第二列为字符串
83                                 //对于数字cell.getCellType的值为HSSFCell.CELL_TYPE_NUMERIC,为0
84                                 //对于字符串cell.getCellType的值为HSSFCell.CELL_TYPE_STRING,为1
85                                 //完整的类型列表请查看api
86                                 String content = cell.getCellType()==HSSFCell.CELL_TYPE_NUMERIC?cell.getNumericCellValue()+"":cell.getStringCellValue();
87                                 System.out.println(content);
88                         }
89                 }
90         }
91 
92 }

下面是创建一个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 }
原文地址:https://www.cnblogs.com/wqsbk/p/4887099.html