Poi创建excel文件
所需jar:poi-3.11-20141221.jar commons-io-2.2.jar
public class PoiExpExcel {
/**
* POI生成Excel文件
*/
public static void main(String[] args) {
String[] title = {"id","name","sex"};
//新建工作簿
HSSFWorkbook workbook = new HSSFWorkbook();
//新建sheet
HSSFSheet sheet = workbook.createSheet();
//创建第一行
HSSFRow row = sheet.createRow(0);
HSSFCell cell = null;
//创建第一行id,name,sex
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 cell2 = nextrow.createCell(0);
cell2.setCellValue("a" + i);
cell2 = nextrow.createCell(1);
cell2.setCellValue("user" + i);
cell2 = nextrow.createCell(2);
cell2.setCellValue("男");
}
//创建excel
File file = new File("e:/poi_test.xls");
try {
file.createNewFile();
//存入excel
FileOutputStream stream = FileUtils.openOutputStream(file);
workbook.write(stream);
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
2.POI读取excel里的内容
public class PoiReadExcel {
/**
* poi读取excel
*/
public static void main(String[] args) {
File file = new File("e:/poi_test.xls");
try {
HSSFWorkbook workbook =
new HSSFWorkbook(FileUtils.openInputStream(file));
//获取第一个工作表workbook.getSheet("Sheet0");
// HSSFSheet sheet = workbook.getSheet("Sheet0");
//获取默认的第一个sheet
HSSFSheet sheet = workbook.getSheetAt(0);
int firstRowNum = 0;
//获取sheet里最后一行行号
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);
String value = cell.getStringCellValue();
System.out.print(value + " ");
}
System.out.println();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
原文地址:http://hatch.blog.51cto.com/9349645/1669822