Java POI 实现Excel文件读写操作
写操作:
package com.zhao.poi;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
public class PoiExcle {
/*
*POI写入Excle文件内容
*/
public static void main(String[] args) {
//创建工作薄
HSSFWorkbook workbook=new HSSFWorkbook();
//创建sheet
HSSFSheet sheet=workbook.createSheet();
//创建第一行row
HSSFRow header=sheet.createRow(0);
//创建单元格并插入表头
HSSFCell cell=null;
String[] infos={"id","name","gender"};
for(int i=0;i<infos.length;i++){
cell=header.createCell(i);
cell.setCellValue(infos[i]);
}
//
HSSFRow body=null;
for(int i=1;i<=10;i++){
body=sheet.createRow(i);
cell=body.createCell(0);
cell.setCellValue(i+"");
cell=body.createCell(1);
cell.setCellValue("user_"+i);
cell=body.createCell(2);
cell.setCellValue(i+"");
}
//创建文件
File file=new File("D:\\poi_1119.xls");
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//文件输出流
try {
FileOutputStream stream=FileUtils.openOutputStream(file);
//写入
workbook.write(stream);
//关闭输出流
stream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
读操作:
package com.zhao.poi;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
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;
public class PoiRead {
public static void main(String[] args) {
//获取文件
File file=new File("D:\\poi_1119.xls");
//文件输入流
try {
FileInputStream stream=FileUtils.openInputStream(file);
//工作薄
HSSFWorkbook workbook=new HSSFWorkbook(stream);
//Sheet
//HSSFSheet sheet=workbook.getSheet("sheet0");
HSSFSheet sheet=workbook.getSheetAt(0);
//
int firstRowNumber=0;
int lastRowNumber=sheet.getLastRowNum();
for(int i=firstRowNumber;i<lastRowNumber;i++){
HSSFRow row=sheet.getRow(i);
int firstCellNumber=0;
int lastCellNumber=row.getLastCellNum();
//
for(int j=firstCellNumber;j<lastCellNumber;j++){
HSSFCell cell=row.getCell(j);
String value=cell.getStringCellValue();
System.out.print(value+"\t");
}
System.out.println("");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}