很简单的Demo,主要是为了熟悉API,及基本的操作。
1.创建Excel文件:
package poi_excel_drdc;
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;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* Created by 28906 on 2016/8/5.
*/
public class PoiExcelWrite {
public static void main(String args[]){
//创建title行
String[] title={"A","B","C"};
//创建工作簿
HSSFWorkbook wb = new HSSFWorkbook();
//创建sheet
HSSFSheet sheet = wb.createSheet();
//创建行
HSSFRow row = sheet.createRow(0);
//创建单元格
HSSFCell cell = null;
//写title行
for(int i=0;i<title.length;i++){
cell = row.createCell(i);
cell.setCellValue(title[i]);
}
//写内容
for(int i=1;i<10;i++){
HSSFRow nextRow = sheet.createRow(i);
HSSFCell cell1 = nextRow.createCell(0);
cell1.setCellValue("a"+i);
nextRow.createCell(1).setCellValue("b"+i);
nextRow.createCell(2).setCellValue("c"+i);
}
File file = new File("G:/demo2.xls");
try {
file.createNewFile();
FileOutputStream stream = FileUtils.openOutputStream(file);
wb.write(stream);
stream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
2.read Excel:
package poi_excel_drdc;
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;
import java.io.File;
/**
* Created by 28906 on 2016/8/5.
* poi读取Excel文件,如果是Excel2007则用XSSFWorkBook
*/
public class PoiExcelRead {
public static void main(String args[]){
File file = new File("G:/demo2.xls");
try {
//创建工作簿
HSSFWorkbook wb = new HSSFWorkbook(FileUtils.openInputStream(file));
//sheet
HSSFSheet sheet = wb.getSheetAt(0);
int firstRowNum = 0;
int lastRowNum = sheet.getLastRowNum();
for(int i=firstRowNum;i<lastRowNum;i++){
HSSFRow row = sheet.getRow(i);
//获取最大列号
int lastCellNum = row.getLastCellNum();
for(int j=0;j<lastCellNum;j++){
HSSFCell cell = row.getCell(j);
System.out.print(cell.getStringCellValue()+" ");
}
System.out.println();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}