java使用Apache POI操作excel文件
- 官方介绍
- 需要的jar包

)并不包含在POI提供的jar包中,需要单独下载,否则程序会抛出异常:java.lang.ClassNotFoundException:org.apache.xmlbeans.XmlOptions。
- 具体代码
public static void createWorkbook() throws IOException {
Workbook wb = new HSSFWorkbook();
String safeName1 = WorkbookUtil.createSafeSheetName("[O'sheet1]");
Sheet sheet1 = wb.createSheet(safeName1);
CreationHelper createHelper = wb.getCreationHelper();
// Create a row and put some cells in it. Rows are 0 based.
Row row = sheet1.createRow((short) 0);
// Create a cell and put a value in it.
Cell cell = row.createCell(0);
cell.setCellValue(1234);
// Or do it on one line.
row.createCell(2).setCellValue(
createHelper.createRichTextString("This is a string"));
row.createCell(3).setCellValue(true);
// we style the second cell as a date (and time). It is important to
// create a new cell style from the workbook otherwise you can end up
// modifying the built in style and effecting not only this cell but
// other cells.
CellStyle cellStyle = wb.createCellStyle();
cellStyle.setDataFormat(createHelper.createDataFormat().getFormat(
"m/d/yy h:mm"));
cell = row.createCell(1);
cell.setCellValue(new Date());
cell.setCellStyle(cellStyle);
// you can also set date as java.util.Calendar
CellStyle cellStyle1 = wb.createCellStyle();
cellStyle1.setDataFormat(createHelper.createDataFormat().getFormat(
"yyyyMMdd HH:mm:ss"));
cellStyle1.setBorderBottom(CellStyle.BORDER_THIN);
cellStyle1.setBottomBorderColor(IndexedColors.BLACK.getIndex());
cellStyle1.setBorderLeft(CellStyle.BORDER_THIN);
cellStyle1.setLeftBorderColor(IndexedColors.GREEN.getIndex());
cellStyle1.setBorderRight(CellStyle.BORDER_THIN);
cellStyle1.setRightBorderColor(IndexedColors.BLUE.getIndex());
cellStyle1.setBorderTop(CellStyle.BORDER_MEDIUM_DASHED);
cellStyle1.setTopBorderColor(IndexedColors.BLACK.getIndex());
cell = row.createCell(4);
cell.setCellValue(Calendar.getInstance());
cell.setCellStyle(cellStyle1);
FileOutputStream fileOut = new FileOutputStream("e:/test/workbook.xls");
wb.write(fileOut);
fileOut.close();
}
读取excel文件的内容:
public static void readExcel() throws InvalidFormatException, IOException {
// Use a file
Workbook wb1 = WorkbookFactory.create(new File("e:/test/userinfo.xls"));
Sheet sheet = wb1.getSheetAt(0);
// Decide which rows to process
// int rowStart = Math.min(10, sheet.getFirstRowNum());
// int rowEnd = Math.max(40, sheet.getLastRowNum());
int rowStart = sheet.getLastRowNum();
int rowEnd = sheet.getLastRowNum() + 1;
logger.info(sheet.getFirstRowNum());
logger.info(sheet.getLastRowNum());
for (int rowNum = rowStart; rowNum < rowEnd; rowNum++) {
Row r = sheet.getRow(rowNum);
int lastColumn = Math.max(r.getLastCellNum(), 10);
logger.info(lastColumn);
// To get the contents of a cell, you first need to know what kind
// of cell it is (asking a string cell for its numeric contents will
// get you a NumberFormatException for example). So, you will want
// to switch on the cell's type, and then call the appropriate
// getter for that cell.
for (int cn = 0; cn < lastColumn; cn++) {
// Cell cell = r.getCell(cn, Row.RETURN_BLANK_AS_NULL);
Cell cell = r.getCell(cn);
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
logger.info(cell.getRichStringCellValue().getString());
break;
case Cell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
logger.info(cell.getDateCellValue());
} else {
logger.info(cell.getNumericCellValue());
}
break;
case Cell.CELL_TYPE_BOOLEAN:
logger.info(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_FORMULA:
logger.info(cell.getCellFormula());
break;
default:
logger.info("empty");
}
}
}
}
下面给出一个具体的例子,实例中的excel文件内容如下:

public static void readUserInfo() throws InvalidFormatException,
IOException {
String[] titles = { "收费编号", "收费性质", "姓名", "家庭住址", "工作单位", "电话", "手机",
"小区楼号", "单元号", "楼层", "房间号", "建筑面积(㎡)", "面积依据", "A面积", "A超",
"A轻体", "B面积", "B超", "B轻体", "用户编号", "所属楼前表表号" }; //用来存储标题和顺序的map,key为标题,value为顺序号
Map<String, Integer> titleMap = new HashMap<String, Integer>();
//将既定顺序写入map
for (int i=0 ; i<titles.length; i++) {
titleMap.put(titles[i], i);
} Workbook wb = WorkbookFactory.create(new File("e:/test/userinfo.xls"));
for (int numSheet = 0; numSheet < wb.getNumberOfSheets(); numSheet++) {
Sheet xSheet = wb.getSheetAt(numSheet);
if (xSheet == null) {
continue;
} // 获取第一行的标题内容
Row tRow = xSheet.getRow(0);
//存储标题顺序的数组
Integer[] titleSort = new Integer[tRow.getLastCellNum()]; //循环标题
for (int titleNum = 0; titleNum < tRow.getLastCellNum(); titleNum++) {
Cell tCell = tRow.getCell(titleNum);
String title = "";
if (tCell == null || "".equals(tCell)) { } else if (tCell.getCellType() == XSSFCell.CELL_TYPE_BOOLEAN) {// 布尔类型处理
// logger.info(xCell.getBooleanCellValue());
} else if (tCell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC) {// 数值类型处理
title = doubleToString(tCell.getNumericCellValue());
} else {// 其他类型处理
title = tCell.getStringCellValue();
}
//通过获取的标题,从map中读取顺讯号,写入保存标题顺序号的数组
Integer ts = titleMap.get(title);
if (ts != null) {
titleSort[titleNum] = ts;
}
} // 循环行Row
for (int rowNum = 1; rowNum < xSheet.getLastRowNum() + 1; rowNum++) {
Row xRow = xSheet.getRow(rowNum);
if (xRow == null) {
continue;
}
// 循环列Cell
String[] v = new String[titleSort.length]; for (int cellNum = 0; cellNum < titleSort.length; cellNum++) {
Cell xCell = xRow.getCell(cellNum);
String value = "";
if (xCell == null || "".equals(xCell)) { } else if (xCell.getCellType() == XSSFCell.CELL_TYPE_BOOLEAN) {// 布尔类型处理
logger.info(xCell.getBooleanCellValue());
} else if (xCell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC) {// 数值类型处理
value = doubleToString(xCell.getNumericCellValue());
} else {// 其他类型处理
value = xCell.getStringCellValue();
} //按照标题顺序的编号来存储每一行记录
v[titleSort[cellNum]] = value;
// logger.info("v[" + titleSort[cellNum] + "] = " + v[titleSort[cellNum]]);
} //循环结果数组,获取的与既定顺序相同
for (int i = 0; i < v.length; i++) {
logger.info(v[i]);
}
}
}
}
上段程序中用到的工具类doubleToString(将excel中的double类型转为String类型,处理了科学计数法形式的数):
private static String doubleToString(double d) {
String str = Double.valueOf(d).toString();
// System.out.println(str);
String result = "";
if (str.indexOf("E") > 2) {
int index = str.indexOf("E");
int power = Integer.parseInt(str.substring(index + 1));
BigDecimal value = new BigDecimal(str.substring(0, index));
value = value.movePointRight(power);
result = value.toString();
} else {
if (str.indexOf(".0") > 0)
result = str.substring(0, str.indexOf(".0"));
else
result = str;
}
return result;
}
目前对于POI的应用只限于此,并没有再深入,以后写了新的相关内容会继续补充,请大大们批评指正!
java使用Apache POI操作excel文件的更多相关文章
- 如何用Apache POI操作Excel文件-----如何对一个单元格加注解?
有的时候,我们需要通过操作Apache POI,在生成Cell数据的同时,能对其生成的Cell,加上注解(comments),类似于下面的. 那么对于这种情况,我们的代码应该如何写呢? 借花献佛,我就 ...
- 如何用Apache POI操作Excel文件-----如何在已有的Excel文件中插入一行新的数据?
在POI的第一节入门中,我们提供了两个简单的例子,一个是如何用Apache POI新建一个工作薄,另外一个例子是,如果用Apache POI新建一个工作表.那么在这个章节里面,我将会给大家演示一下,如 ...
- 如何用Apache POI操作Excel文件-----如何用Apache POI 画一个离散图
有的时候,我们需要Excel中的数据,通过一个图画,可视化的表现出来. 那么这个时候,应该如何做呢?现在就借花献佛,以Apache POI自己提供的一个例子为例,给大家演示一下POI的API 如何画图 ...
- (6) 如何用Apache POI操作Excel文件-----POI-3.10的一个和注解(comment)相关的另外一个bug
如果POI-3.10往一个工作表(sheet)里面插入数据的话,需要注意了,其有一个不太被容易发现的bug. 被插入的工作表(sheet)里面的单元格没有包含任何的注解(comment)的时候,插入一 ...
- 使用Apache POI操作Excel文件---在已有的Excel文件中插入一行新的数据
package org.test; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundEx ...
- java使用POI操作excel文件,实现批量导出,和导入
一.POI的定义 JAVA中操作Excel的有两种比较主流的工具包: JXL 和 POI .jxl 只能操作Excel 95, 97, 2000也即以.xls为后缀的excel.而poi可以操作Exc ...
- 项目一:第四天 1、快递员的条件分页查询-noSession,条件查询 2、快递员删除(逻辑删除) 3、基于Apache POI实现批量导入区域数据 a)Jquery OCUpload上传文件插件使用 b)Apache POI读取excel文件数据
1. 快递员的条件分页查询-noSession,条件查询 2. 快递员删除(逻辑删除) 3. 基于Apache POI实现批量导入区域数据 a) Jquery OCUpload上传文件插件使用 b) ...
- 利用Apache POI操作Excel
最近在做接口,有个功能是利用Excel导入汽车发动机所需零件信息到线上系统中.简单回顾一下之前学过的用java操作Excel. 1.maven配置Apache POI pom.xml中配置POIjar ...
- Java使用POI操作Excel文件
1.简介 Apache POI是Apache软件基金会的开放源码函式库,POI提供API给Java程序对Microsoft Office格式文件读和写的功能. 2.依赖的jar包 <!-- ex ...
随机推荐
- WP开发笔记——WP7 SDK使用技巧
俗话说的好,工欲善其事,必先利其器. 入门WP开发之前,免不了要先接触开发环境和开发工具.使用WP7 SDK进行开发,我们需要掌握SDK的一些实用技巧,以便我们的开发. 一.开启/关闭电脑键盘输入 W ...
- iOS界面布局设计
参考资料: 1. 谈谈如何学习ios 8的界面和布局设计 2. iOS 8 Auto Layout界面布局系列 3. 为iPhone 6设计自适应布局 4. 几张图弄明白iOS布局中的尺寸问题
- Jquery Slick幻灯片插件
slick 是一个基于 jQuery 的幻灯片插件,具有以下特点: 支持响应式 浏览器支持 CSS3 时,则使用 CSS3 过度/动画 支持移动设备滑动 支持桌面浏览器鼠标拖动 支持循环 支持左右控制 ...
- Window 8.1 计时器功能及图片切换
<Canvas Margin="450,0" Width="795" Grid.Column="1"> <Image Ma ...
- 【转载】DataGridView 使用集合作为数据源,并同步更新
原文地址:http://hi.baidu.com/netyro/item/7340640e36738a813c42e239 今天做项目时遇到一个挠头的问题,当DataGridView的数据源为泛型集合 ...
- 两个Activity之间的交互startActivityForResult的使用
代码如下: package com.zzw.teststartintentforrequest; import android.app.Activity; import android.content ...
- Delphi XE5教程4:程序和单元概述
内容源自Delphi XE5 UPDATE 2官方帮助<Delphi Reference>,本人水平有限,欢迎各位高人修正相关错误!也欢迎各位加入到Delphi学习资料汉化中来,有兴趣者可 ...
- SQL Server 数据库身份认证以及包含数据库
首先分为SQL Server 认证与Windows 身份认证. SQL Server 认证可以运行以下语句来查询 select * from sys.sql_logins 管理员可以直接修改密码,但无 ...
- sysfs->sys简单介绍
Sys节点 1:sysfs 是 Linux 内核中设计较新的一种虚拟的基于内存的文件系统, sysfs 的挂载点 /sys 目录结构. 2:/sys 文件系统下的目录结构 /sys 下的目录结构是经过 ...
- php 彩票类 lottery
<?php /* * For the full copyright and license information, please view the LICENSE * file that wa ...