1、poi-excel的第一个例子,写一个字符串到excel表
Workbook wb=new HSSFWorkbook()
Sheet sheet = wb.createSheet("第一个sheet页")
Row row = sheet.createRow(0)
Cell cell = row.createCell(0)
cell.setCellValue("1135746")
FileOutputStream fileOut=new FileOutputStream("C:\\Users\\Administrator\\Desktop\\my.xls")
wb.write(fileOut)
fileOut.close()
wb.close()
2、poi-excel的第二个例子,写不同的类型到excel表
Workbook wb=new HSSFWorkbook()
Sheet sheet = wb.createSheet("表一")
Row row = sheet.createRow(0)
Cell cell = row.createCell(0)
cell.setCellValue(new Date())
CreationHelper creationHelper=wb.getCreationHelper()
CellStyle cellStyle = wb.createCellStyle()
cellStyle.setDataFormat(creationHelper.createDataFormat().getFormat("yyyy-MM-dd hh:mm:ss"))
cell.setCellStyle(cellStyle)
Cell cell2 = row.createCell(1)
cell2.setCellValue("我叫王明远")
Cell cell3 = row.createCell(2)
cell3.setCellValue(false)
Cell cell4 = row.createCell(3)
cell4.setCellValue(Calendar.getInstance())
cell4.setCellStyle(cellStyle)
FileOutputStream fileOutputStream=new FileOutputStream("C:\\Users\\Administrator\\Desktop\\my.xls")
wb.write(fileOutputStream)
fileOutputStream.close()
System.out.println("输出完成")
3、poi-excel的第三个例子,从excel表中遍历数据
@SuppressWarnings("resource")
public static void main(String[] args) throws IOException {
InputStream is = new FileInputStream("C:\\Users\\Administrator\\Desktop\\王明远-月度总结及计划.xls");
POIFSFileSystem fs = new POIFSFileSystem(is);
HSSFWorkbook workbook = new HSSFWorkbook(fs);
HSSFSheet hssfSheet = workbook.getSheetAt(0);
if (hssfSheet == null) {
return;
}
for (int i = 0; i < hssfSheet.getLastRowNum(); i++) {
HSSFRow hssfRow = hssfSheet.getRow(i);
if (hssfRow == null) {
continue;
}
for (int j = 0; j < hssfRow.getLastCellNum(); j++) {
HSSFCell cell = hssfRow.getCell(j);
if (cell == null) {
continue;
}
System.out.println(" "+getValue(cell));
}
}
}
@SuppressWarnings({ "unused", "deprecation" })
private static String getValue(HSSFCell cell) {
if (cell.getCellType() == HSSFCell.CELL_TYPE_BOOLEAN) {
return String.valueOf(cell.getBooleanCellValue());
} else if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
return String.valueOf(cell.getNumericCellValue());
} else {
return String.valueOf(cell.getStringCellValue());
}
}
InputStream is = new FileInputStream("C:\\Users\\Administrator\\Desktop\\王明远-月度总结及计划.xls");
POIFSFileSystem fs = new POIFSFileSystem(is);
HSSFWorkbook workbook = new HSSFWorkbook(fs);
ExcelExtractor excelExtractor=new ExcelExtractor(workbook);
excelExtractor.setIncludeSheetNames(false);
System.out.println(excelExtractor.getText());
workbook.close();