Poi建立excel文件ide
所需jar:poi-3.11-20141221.jar commons-io-2.2.jar
excel
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裏的內容ci
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();
}
}
}
get