poi包操作Excel
在java中经常会有对数据库的操作,当我们需要一个报表,统计时,就需要对excel进行操作。
(因为公司中肯定不止你一个工作人员,还有老板,销售,他们需要查看数据。大多数人懂的的是excel表格)
对xls的版本操作!
一、 进行导出操作
1、进行pom依赖的导出(poi)
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
</dependency>
- 还需要格外的两个依赖(你如果只是测试可以不要)
文件上传的依赖
text1 2 3 4<dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> </dependency>时间格式转换的依赖
text1 2 3 4<dependency> <groupId>joda-time</groupId> <artifactId>joda-time</artifactId> </dependency>
2、xls操作类
1)创建xls对象表格
Workbook workbook = new HSSFWorkbook();
使用xlsx改对象就行(其他操作一模一样)
Workbook workbook = new XSSFWorkbook();
2)如要新建一名为"会员登录统计"的工作表,其语句为:
Sheet sheet = workbook.createSheet("会员登录统计");
- 代表了设置xls中的
3)创建行
(0表示创建第一行)
Row row = sheet.createRow(0);
4)创建列
(先创建行再创建列,就有了单元格,然后设置值)
0代表第一列
Cell cell = row.createCell(0);
cell11.setCellValue("今日人数");
5)将excel以流的方式导出
(out为FileOutputStream流)
workbook.write(out);
二、导出测试demo
代码如下
@Test
public void testWrite03() throws IOException {
// 创建新的Excel 工作簿
Workbook workbook = new HSSFWorkbook();
// 在Excel工作簿中建一工作表,其名为缺省值 Sheet0
//Sheet sheet = workbook.createSheet();
// 如要新建一名为"会员登录统计"的工作表,其语句为:
Sheet sheet = workbook.createSheet("会员登录统计");
// 创建行(row 1)
Row row1 = sheet.createRow(0);
// 创建单元格(col 1-1)
Cell cell11 = row1.createCell(0);
cell11.setCellValue("今日人数");
// 创建单元格(col 1-2)
Cell cell12 = row1.createCell(1);
cell12.setCellValue(666);
// 创建行(row 2)
Row row2 = sheet.createRow(1);
// 创建单元格(col 2-1)
Cell cell21 = row2.createCell(0);
cell21.setCellValue("统计时间");
//创建单元格(第三列)
Cell cell22 = row2.createCell(1);
String dateTime = new DateTime().toString("yyyy-MM-dd HH:mm:ss");
cell22.setCellValue(dateTime);
// 新建一输出文件流(注意:要先创建文件夹)
FileOutputStream out = new FileOutputStream("d:/test-write03.xls");
// 把相应的Excel 工作簿存盘
workbook.write(out);
// 操作结束,关闭文件
out.close();
System.out.println("文件生成成功");
}
三、导入代码
特别简单就只需要把excel文件流放入对象直接读取
Workbook workbook = new HSSFWorkbook(文件流);
然后操作ok

评论
登录后即可评论
分享你的想法,与作者互动
暂无评论