操作之前需把jar包导入工程里
直接看代码(用的junit测试成功)
(还要在本地新建E:/file/testResult.xls)
一:写数据
/**
* 写excle数据
*/
@Test
public void test1() {
List<LytBbsTopic> resultList = topicDao.getAllBbsTopic();
HSSFWorkbook workbook = new HSSFWorkbook();//创建excel文件对象
Sheet sheet = workbook.createSheet();//创建sheet对象
Row row;
row = sheet.createRow(0);//第一行,标题
row.createCell(0).setCellValue("title");
row.createCell(1).setCellValue("content");
row.createCell(2).setCellValue("pic");
row.createCell(3).setCellValue("addTime");
for (int i = 1, len = resultList.size(); i <len; i++) {
//循环创建数据行
row = sheet.createRow(i);
row.createCell(0).setCellValue(resultList.get(i).getTitle());
row.createCell(1).setCellValue(resultList.get(i).getContent());
row.createCell(2).setCellValue(resultList.get(i).getPic());
row.createCell(3).setCellValue(format.format((Date)resultList.get(i).getAddTime()));
}
try {
FileOutputStream fos = new FileOutputStream("E:/file/testResult.xls");
workbook.write(fos);//写文件
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
二:读数据
/**
* 读excle数据
*/
@Test
public void test2() {
List<LytBbsTopic> resultList = new ArrayList<LytBbsTopic>();
try {
HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(new File("E:/file/testResult.xls")));
Sheet sheet = workbook.getSheetAt(0);//读取第一个sheet
for (int i = 1; i <sheet.getPhysicalNumberOfRows(); i++) {
//逐行处理excel数据
Row row = sheet.getRow(i);
Cell cell0 = row.getCell(0);// 相对于上一个方法 获取的title
Cell cell1 = row.getCell(1);// content
Cell cell2 = row.getCell(2);// pic
Cell cell3 = row.getCell(3);// addTime
System.out.println(cell2.toString()+"\t"+cell3.toString());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}