java操作数据 “ 读写 ” excle文件

本文介绍如何使用Java进行Excel文件的数据读取和写入操作。通过示例代码展示了利用HSSFWorkbook创建Excel文件并写入数据的过程,同时演示了如何从已有的Excel文件中读取数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

操作之前需把jar包导入工程里 

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();
}           

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值