您的位置:首页 > 编程语言 > Java开发

java使用poi操作excel(读、写)

2013-04-26 10:08 190 查看
摘要:
Jakarta POI 是apache的子项目,目标是处理ole2对象。它提供了一组操纵Windows文档的Java API

目前比较成熟的是HSSF接口,处理MS Excel(97-2007)对象。它不象我们仅仅是用csv生成的没有格式的可以由Excel转换的东西,而是真正的Excel对象,你可以控制一些属性如sheet,cell等等。

HSSF 是Horrible SpreadSheet Format的缩写,也即“讨厌的电子表格格式”。也许HSSF的名字有点滑稽,就本质而言它是一个非常严肃、正规的API。通过HSSF,你可以用纯Java代码来读取、写入、修改Excel文件。

HSSF 为读取操作提供了两类API:usermodel和eventusermodel,即“用户模型”和“事件-用户模型”。前者很好理解,后者比较抽象,但操作效率要高得多。

准备工作:

1.下载所需jar包 下载链接

2.熟悉excel表结构

3.为了让大家能更好更方便的操作excel体验其强大的功能,专为大家提供了更多功能更完整的源码 下载链接

编码实现:

1).读取excel

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

/**
* Excel文件数据的读取
*
* @author yaohucaizi
*/
public class ExcelUtil {

public List<String[]> readExcel(String filePath) {
List<String[]> dataList = new ArrayList<String[]>();
boolean isExcel2003 = true;
if (isExcel2007(filePath)) {
isExcel2003 = false;
}
File file = new File(filePath);
InputStream is = null;
try {
is = new FileInputStream(file);
} catch (FileNotFoundException ex) {
Logger.getLogger(ExcelUtil.class.getName()).log(Level.SEVERE, null, ex);
}
Workbook wb = null;
try {
wb = isExcel2003 ? new HSSFWorkbook(is) : new XSSFWorkbook(is);
} catch (IOException ex) {
Logger.getLogger(ExcelUtil.class.getName()).log(Level.SEVERE, null, ex);
}
Sheet sheet = wb.getSheetAt(0);
int totalRows = sheet.getPhysicalNumberOfRows();
int totalCells = 0;
if (totalRows >= 1 && sheet.getRow(0) != null) {
totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
}
for (int r = 0; r < totalRows; r++) {
Row row = sheet.getRow(r);
if (row == null) {
continue;
}
String[] rowList = new String[totalCells];
for (int c = 0; c < totalCells; c++) {
Cell cell = row.getCell(c);
String cellValue = "";
if (cell == null) {
rowList[c] = (cellValue);
continue;
}
cellValue = ConvertCellStr(cell, cellValue);
rowList[c] = (cellValue);
}
dataList.add(rowList);
}
return dataList;
}

private String ConvertCellStr(Cell cell, String cellStr) {
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
// 读取String
cellStr = cell.getStringCellValue().toString();
break;
case Cell.CELL_TYPE_BOOLEAN:
// 得到Boolean对象的方法
cellStr = String.valueOf(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_NUMERIC:
// 先看是否是日期格式
if (DateUtil.isCellDateFormatted(cell)) {
// 读取日期格式
cellStr = formatTime(cell.getDateCellValue().toString());
} else {
// 读取数字
cellStr = String.valueOf(cell.getNumericCellValue());
}
break;
case Cell.CELL_TYPE_FORMULA:
// 读取公式
cellStr = cell.getCellFormula().toString();
break;
}
return cellStr;
}

private boolean isExcel2007(String fileName) {
return fileName.matches("^.+\\.(?i)(xlsx)$");
}

private String formatTime(String s) {
SimpleDateFormat sf = new SimpleDateFormat("EEE MMM dd hh:mm:ss z yyyy", Locale.ENGLISH);
Date date = null;
try {
date = sf.parse(s);
} catch (ParseException ex) {
Logger.getLogger(ExcelUtil.class.getName()).log(Level.SEVERE, null, ex);
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String result = sdf.format(date);
return result;
}

public static void main(String[] args) throws IOException {
ExcelUtil re = new ExcelUtil();
//	List<String[]> list = re.readExcel("c:/群组.xls");
List<String[]> list = re.readExcel("c:/群组.xlsx");
if (list != null) {
for (int i = 0; i < list.size(); i++) {
System.out.println("第" + (i + 1) + "行");
String[] cellList = list.get(i);
for (int j = 0; j < cellList.length; j++) {
System.out.print("\t第" + (j + 1) + "列值:");
System.out.println(cellList[j]);
}
}
}
}
}


2).写入excel

import java.io.FileOutputStream;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

/**
* Excel文件数据的写入
*
* @author yaohucaizi
*/
public class WriteExcel {

public void write(String filePath) throws Exception {
List<List<String>> dateList = new ListSource().listSource();
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("sheet");// 添加sheet
// 表格样式
HSSFCellStyle style = wb.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 指定单元格居中对齐
// // 边框
// style.setBorderBottom(HSSFCellStyle.BORDER_MEDIUM);
// style.setBorderTop(HSSFCellStyle.BORDER_MEDIUM);
// style.setBorderLeft(HSSFCellStyle.BORDER_MEDIUM);
// style.setBorderRight(HSSFCellStyle.BORDER_MEDIUM);
// //设置字体
// HSSFFont f = wb.createFont();
// f.setFontHeightInPoints((short)10);
// f.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
// style.setFont(f);
// //设置列宽
// sheet.setColumnWidth((short)0, (short)9600);
// sheet.setColumnWidth((short)1, (short)4000);
// sheet.setColumnWidth((short)2, (short)8000);
// sheet.setColumnWidth((short)3, (short)8000);

// 在索引0的位置创建第一行

for (int i = 0; i < dateList.size(); i++) {
HSSFRow row = sheet.createRow(i);
List<String> list = dateList.get(i);
for (int j = 0; j < list.size(); j++) {
HSSFCell cell = row.createCell(j);
cell.setCellValue(list.get(j));
cell.setCellStyle(style);
}
}
// 导出文件
FileOutputStream fout = new FileOutputStream(filePath);
wb.write(fout);
fout.close();
}

public static void main(String[] args) throws Exception {
WriteExcel we = new WriteExcel();
we.write("C:/群组.xls");
}
}


3).ListSource数据资源类

import java.util.ArrayList;
import java.util.List;

/**
* 生成插入数据list集合
*
* @author yaohucaizi
*/
public class ListSource {

public List<List<String>> listSource() {
List<List<String>> totalList = new ArrayList<List<String>>();
for (int i = 0; i < 10; i++) {
List<String> list = new ArrayList<String>();
for (int j = 0; j < 5; j++) {
String str = "";
String source = getStr(j, str);
list.add(source);
}
totalList.add(list);
}
return totalList;
}

private String getStr(int j, String str) {
switch (j) {
case 0:
str = "姓名";
break;
case 1:
str = "年龄";
break;
case 2:
str = "地址";
break;
case 3:
str = "电话";
break;
case 4:
str = "爱好";
break;
}
return str;
}
}


如果使用maven项目管理,pom.xml中代码为:

<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.7</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>ooxml-schemas</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>org.apache.xmlbeans</groupId>
<artifactId>xmlbeans</artifactId>
<version>2.3.0</version>
</dependency>


获取功能更多更完整的poi操作excel源代码
下载链接

到此为止excel的读、写操作已完成,如有疑问之处可以给我留言,我会给大家详细的解释。

如转载此篇文章请注明作者及文章出处,版权所有、违者必究,谢谢配合!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: