先来看看读取操作,先创建HSSFWorkbook对象(xls格式),如果是xlsx格式,需要XSSFWorkbook对象,然后获取工作簿HSSFSheet,然后遍历工作簿。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
public
static
void
readExcel(File f){
InputStream instream =
null
;
HSSFWorkbook workbook;
//POI解析xls文件的工具类,解析xlsx格式的工具类是XHSSFWorkbook
try
{
try
{
instream =
new
FileInputStream(f);
workbook =
new
HSSFWorkbook(instream);
HSSFSheet sheet = workbook.getSheetAt(
0
);
for
(Row row : sheet){
for
(Cell cell : row){
System.out.println(cell.getStringCellValue());
}
}
}
finally
{
if
(instream!=
null
){
instream.close();
}
}
}
catch
(FileNotFoundException e) {
e.printStackTrace();
}
catch
(IOException e) {
e.printStackTrace();
}
}
|
再来看写入操作, 先创建HSSFWorkbook对象,然后creatSheet(),然后creatRow()和creatCell(),最后写出HSSFWorkbook
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
public
static
void
writeExcel(File f){
OutputStream outStream =
null
;
HSSFWorkbook workbook ;
try
{
try
{
outStream =
new
FileOutputStream(f);
workbook =
new
HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet();
Row row =
null
;
Cell cell =
null
;
for
(
int
i =
0
; i <
100
; i++){
row = sheet.createRow(i);
for
(
int
j =
0
; j <
100
; j++){
cell = row.createCell(j);
cell.setCellValue(
"第"
+String.valueOf(i)+
"行第"
+String.valueOf(j)+
"列"
);
}
}
workbook.write(outStream);
}
finally
{
if
(outStream!=
null
){
outStream.close();
}
}
}
catch
(IOException e){}
}
|