excel2003和excel2007文件的创建和读取
excel2003和excel2007文件的创建和读取在项目中用的很多,首先我们要了解excel的常用组件和基本操作步骤。
常用组件如下所示:
HSSFWorkbook excel的文档对象 HSSFSheet excel的表单 HSSFRow excel的行 HSSFCell excel的格子单元 HSSFFont excel字体 HSSFDataFormat 日期格式 HSSFHeader sheet头 HSSFFooter sheet尾(只有打印的时候才能看到效果) 样式: HSSFCellStyle cell样式 辅助操作包括: HSSFDateUtil 日期 HSSFPrintSetup 打印 HSSFErrorConstants 错误信息表
常用组件
基本操作步骤如下:
首先,理解一下一个Excel的文件的组织形式,一个Excel文件对应于一个workbook(HSSFWorkbook),一个workbook可以有多个 sheet(HSSFSheet)组成,一个sheet是由多个row(HSSFRow)组成,一个row是由多个cell(HSSFCell)组成。
1、用HSSFWorkbook打开或者创建“Excel文件对象”
2、用HSSFWorkbook对象返回或者创建Sheet对象
3、用Sheet对象返回行对象,用行对象得到Cell对象
4、对Cell对象读写。
生成excel的例子如下:
复制代码
//创建HSSFWorkbook对象
HSSFWorkbook wb = new HSSFWorkbook();
//创建HSSFSheet对象
HSSFSheet sheet = wb.createSheet("sheet0");
//创建HSSFRow对象
HSSFRow row = sheet.createRow(0);
//创建HSSFCell对象
HSSFCell cell=row.createCell(0);
//设置单元格的值
cell.setCellValue("单元格中的中文");
//输出Excel文件
FileOutputStream output=new FileOutputStream("d:\\workbook.xls");
wkb.write(output);
output.flush();
生成excel的例子
今天专门在此通过项目做一个总结,项目结构如图所示:

思路如下:
1、从数据库(mysql)读取数据,获取数据集合;
2、判断文件的后缀是.xls 还是.xlsx ?如果后缀是.xls 则是excel2003,否则为excel2007;
3、excel2003的读取和创建;
4、excel2007的读取和创建;
代码如下:
1、数据库工具类:DBhepler
package com.test.excel.poi.dbutil; import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException; public class DBhepler {
/*String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
String url = "jdbc:sqlserver://127.0.0.1;DatabaseName=Mobile";*/ String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://127.0.0.1:3306/excel"; Connection con = null;
ResultSet res = null; public void DataBase() {
try {
Class.forName(driver);
con = DriverManager.getConnection(url, "root", "ROOT");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
System.err.println("装载 JDBC/ODBC 驱动程序失败。" );
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
System.err.println("无法连接数据库" );
e.printStackTrace();
}
} // 查询
public ResultSet Search(String sql, String str[]) {
DataBase();
try {
PreparedStatement pst =con.prepareStatement(sql);
if (str != null) {
for (int i = 0; i < str.length; i++) {
pst.setString(i + 1, str[i]);
}
}
res = pst.executeQuery(); } catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return res;
} // 增删修改
public int AddU(String sql, String str[]) {
int a = 0;
DataBase();
try {
PreparedStatement pst = con.prepareStatement(sql);
if (str != null) {
for (int i = 0; i < str.length; i++) {
pst.setString(i + 1, str[i]);
}
}
a = pst.executeUpdate();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return a;
} }
DBhepler
2、测试类:TestExcel
package com.test.test;
import com.test.excel.poi.ExcelUtils;
public class TestExcel {
public static void main(String[] args) throws Exception {
ExcelUtils eu = new ExcelUtils();
eu.parseFile();
}
}
TestExcel
3、excel工具类:ExcelUtils
package com.test.excel.poi; import java.util.ArrayList;
import java.util.List; import com.test.excel.poi.entity.Student;
import com.test.excel.poi.service.StuService; public class ExcelUtils { String newFilePath = "f:\\test\\students.xlsx";
String fileCurName = "f:\\test\\ouyy.xlsx";
public void parseFile() throws Exception{
// 通过文件名截取到文件类型
String fileType = fileCurName.substring(fileCurName.lastIndexOf(".")).toLowerCase();
List<Student> list = new ArrayList<Student>();
//1.从数据库读取数据,获取数据集合
list = StuService.getAllByDb(); // 解析2003及WPS格式的的excel文件
if(fileType.equals(".xls") || fileType.equals(".et"))
{
//1.将excel2003文件读取出来
JExcelTool.readExcel2003(fileCurName); //2.创建excel2003
JExcelTool.createExcel2003(list, newFilePath); } // 解析excel2007文件
else if(fileType.equals(".xlsx"))
{
//1.将excel2003文件读取出来
JExcelTool.readExcel2007(fileCurName); //2.创建excel2003
JExcelTool.createExcel2007(list, newFilePath);
}
} public static void main(String[] args) throws Exception {
ExcelUtils eu = new ExcelUtils();
eu.parseFile();
}
}
ExcelUtils
4、excel的解析类:JExcelTool
package com.test.excel.poi; import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
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;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook; import com.test.excel.poi.entity.Student; public class JExcelTool { /**
*
*
* @param filePath D:/students.xls
* @return
*
* @Description:读取文件excel2003
*/
public static List<Student> readExcel2003(String filePath) {
List<Student> list = new ArrayList<Student>();
HSSFWorkbook workbook = null; try {
// 读取Excel文件
InputStream inputStream = new FileInputStream(filePath);
workbook = new HSSFWorkbook(inputStream);
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
} // 循环工作表
for (int numSheet = 0; numSheet < workbook.getNumberOfSheets(); numSheet++) {
HSSFSheet hssfSheet = workbook.getSheetAt(numSheet);
if (hssfSheet == null) {
continue;
}
// 循环行
for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
HSSFRow hssfRow = hssfSheet.getRow(rowNum);
if (hssfRow == null) {
continue;
} // 将单元格中的内容存入集合
Student student = new Student(); HSSFCell cell = hssfRow.getCell(0);
if (cell == null) {
continue;
}
student.setId((int) cell.getNumericCellValue());
cell = hssfRow.getCell(1);
if (cell == null) {
continue;
}
student.setName(cell.getStringCellValue()); cell = hssfRow.getCell(2);
if (cell == null) {
continue;
}
student.setSex(cell.getStringCellValue()); cell = hssfRow.getCell(3);
if (cell == null) {
continue;
}
student.setNum((int) cell.getNumericCellValue()); list.add(student);
}
}
return list;
} /**
*
*getCellFormatValue(row.getCell(0));
* @param list
* @param newFilePath 新的文件 f:/students.xls
*
* @Description: 创造文件excel2003
*/
public static void createExcel2003(List<Student> list,String newFilePath){
// 创建一个Excel文件
HSSFWorkbook workbook = new HSSFWorkbook();
// 创建一个工作表
HSSFSheet sheet = workbook.createSheet("学生表一");
// 添加表头行
HSSFRow hssfRow = sheet.createRow(0);
// 设置单元格格式居中
HSSFCellStyle cellStyle = workbook.createCellStyle();
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 添加表头内容
HSSFCell headCell = hssfRow.createCell(0);
headCell.setCellValue("id");
headCell.setCellStyle(cellStyle); headCell = hssfRow.createCell(1);
headCell.setCellValue("姓名");
headCell.setCellStyle(cellStyle); headCell = hssfRow.createCell(2);
headCell.setCellValue("性别");
headCell.setCellStyle(cellStyle); headCell = hssfRow.createCell(3);
headCell.setCellValue("编号");
headCell.setCellStyle(cellStyle); // 添加数据内容
for (int i = 0; i < list.size(); i++) {
hssfRow = sheet.createRow((int) i + 1);
Student student = list.get(i); // 创建单元格,并设置值
HSSFCell cell = hssfRow.createCell(0);
cell.setCellValue(student.getId());
cell.setCellStyle(cellStyle); cell = hssfRow.createCell(1);
cell.setCellValue(student.getName());
cell.setCellStyle(cellStyle); cell = hssfRow.createCell(2);
cell.setCellValue(student.getSex());
cell.setCellStyle(cellStyle); cell = hssfRow.createCell(3);
cell.setCellValue(student.getNum());
cell.setCellStyle(cellStyle);
} // 保存Excel文件
try {
OutputStream outputStream = new FileOutputStream(newFilePath);
workbook.write(outputStream);
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
} /**
*
*
* @param filePath
* @return
*
* @Description: 读取excel2007
*/
public static List<Student> readExcel2007(String filePath){
List<Student> list = new ArrayList<Student>();
XSSFWorkbook workbook = null; try {
// 读取Excel文件
InputStream inputStream = new FileInputStream(filePath);
workbook = new XSSFWorkbook(inputStream);
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
} // 循环工作表
for (int numSheet = 0; numSheet < workbook.getNumberOfSheets(); numSheet++) {
XSSFSheet hssfSheet = workbook.getSheetAt(numSheet);
if (hssfSheet == null) {
continue;
}
// 循环行
for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
XSSFRow hssfRow = hssfSheet.getRow(rowNum);
if (hssfRow == null) {
continue;
} // 将单元格中的内容存入集合
Student student = new Student(); XSSFCell cell = hssfRow.getCell(0);
if (cell == null) {
continue;
}
student.setId((int) cell.getNumericCellValue());
cell = hssfRow.getCell(1);
if (cell == null) {
continue;
}
student.setName(cell.getStringCellValue()); cell = hssfRow.getCell(2);
if (cell == null) {
continue;
}
student.setSex(cell.getStringCellValue()); cell = hssfRow.getCell(3);
if (cell == null) {
continue;
}
student.setNum((int) cell.getNumericCellValue()); list.add(student);
}
}
return list;
} public static void createExcel2007(List<Student> list,String newFilePath){
// 创建一个Excel文件
XSSFWorkbook workbook = new XSSFWorkbook();
// 创建一个工作表
XSSFSheet sheet = workbook.createSheet("学生表一");
// 添加表头行
XSSFRow xssfRow = sheet.createRow(0);
// 设置单元格格式居中
XSSFCellStyle cellStyle = workbook.createCellStyle();
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 添加表头内容
XSSFCell headCell = xssfRow.createCell(0);
headCell.setCellValue("id");
headCell.setCellStyle(cellStyle); headCell = xssfRow.createCell(1);
headCell.setCellValue("姓名");
headCell.setCellStyle(cellStyle); headCell = xssfRow.createCell(2);
headCell.setCellValue("性别");
headCell.setCellStyle(cellStyle); headCell = xssfRow.createCell(3);
headCell.setCellValue("编号");
headCell.setCellStyle(cellStyle); // 添加数据内容
for (int i = 0; i < list.size(); i++) {
xssfRow = sheet.createRow((int) i + 1);
Student student = list.get(i); // 创建单元格,并设置值
XSSFCell cell = xssfRow.createCell(0);
cell.setCellValue(student.getId());
cell.setCellStyle(cellStyle); cell = xssfRow.createCell(1);
cell.setCellValue(student.getName());
cell.setCellStyle(cellStyle); cell = xssfRow.createCell(2);
cell.setCellValue(student.getSex());
cell.setCellStyle(cellStyle); cell = xssfRow.createCell(3);
cell.setCellValue(student.getNum());
cell.setCellStyle(cellStyle);
} // 保存Excel文件
try {
OutputStream outputStream = new FileOutputStream(newFilePath);
workbook.write(outputStream);
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
} /***
* 获得excel的单元格
* @Description: TODO
* @param @param cell
* @param @return
* @return String
*/
private static String getCellFormatValue(XSSFCell cell)
{
String cellvalue = "";
if (cell != null)
{
// 判断当前Cell的Type
switch (cell.getCellType())
{
// 如果当前Cell的Type为NUMERIC
case XSSFCell.CELL_TYPE_NUMERIC:
case XSSFCell.CELL_TYPE_FORMULA:
{
// 判断当前的cell是否为Date
if (DateUtil.isCellDateFormatted(cell))
{
// 如果是Date类型则,取得该Cell的Date值
Date date = cell.getDateCellValue();
// 把Date转换成本地格式的字符串
Calendar c = Calendar.getInstance();
c.setTime(date);
if(c.get(Calendar.HOUR)==0 && c.get(Calendar.MINUTE)==0 && c.get(Calendar.SECOND) ==0){
cellvalue = new SimpleDateFormat("yyyy-MM-dd").format(date);
}else {
cellvalue = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
}
}
// 如果是纯数字
else
{
// 取得当前Cell的数值
// 是否有小数部分(分开处理)
if(Math.floor(cell.getNumericCellValue())==cell.getNumericCellValue())
{
cellvalue=String.valueOf((long)cell.getNumericCellValue());
}else {
cellvalue = cell.getRawValue();
} }
break;
}
// 如果当前Cell的Type为STRIN
case XSSFCell.CELL_TYPE_STRING:
// 取得当前的Cell字符串
cellvalue = cell.getStringCellValue();
break;
// 默认的Cell值
default:
cellvalue = " ";
}
}
else
{
cellvalue = "";
}
return cellvalue;
} /**
* 判断单元格格式,返回字符串Excel2003
* @param cell
* @return
*/
private static String getCellFormatValue(HSSFCell cell)
{
String cellvalue = "";
if (cell != null)
{
// 判断当前Cell的Type
switch (cell.getCellType())
{
case HSSFCell.CELL_TYPE_NUMERIC: // 数字
// 判断当前的cell是否为Date
if (DateUtil.isCellDateFormatted(cell))
{
// 如果是Date类型则,取得该Cell的Date值
Date date = cell.getDateCellValue();
// 把Date转换成本地格式的字符串
Calendar c = Calendar.getInstance();
c.setTime(date);
if(c.get(Calendar.HOUR)==0 && c.get(Calendar.MINUTE)==0 && c.get(Calendar.SECOND) ==0){
cellvalue = new SimpleDateFormat("yyyy-MM-dd").format(date);
}else {
cellvalue = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
}
}
// 如果是纯数字
else
{
// 是否有小数部分(分开处理)
if(Math.floor(cell.getNumericCellValue())==cell.getNumericCellValue())
{
cellvalue=String.valueOf((long)cell.getNumericCellValue());
}else {
cellvalue = String.valueOf(cell.getNumericCellValue());
}
//System.out.println(cellvalue);
}
break;
case HSSFCell.CELL_TYPE_STRING: // 字符串
cellvalue = cell.getStringCellValue() ;
break;
case HSSFCell.CELL_TYPE_FORMULA: // 公式
cellvalue = cell.getCellFormula();
break;
case HSSFCell.CELL_TYPE_BLANK: // 空值
cellvalue = " ";
break;
case HSSFCell.CELL_TYPE_ERROR: // 故障
cellvalue = " ";
break;
default:
cellvalue = " ";
break;
}
}
else
{
cellvalue = "";
}
return cellvalue;
} }
JExcelTool
5、查询数据库中stu表中所有的数据
package com.test.excel.poi.service; import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List; import com.test.excel.poi.dbutil.DBhepler;
import com.test.excel.poi.entity.Student; public class StuService { /**
* 查询stu表中所有的数据
* @return
*/
public static List<Student> getAllByDb(){
List<Student> list=new ArrayList<Student>();
try {
DBhepler db=new DBhepler();
String sql="select * from stu";
ResultSet rs= db.Search(sql, null);
while (rs.next()) {
int id=rs.getInt("id");
String name=rs.getString("name");
String sex=rs.getString("sex");
int num=rs.getInt("num"); //System.out.println(id+" "+name+" "+sex+ " "+num);
list.add(new Student(id, name, sex, num));
} } catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
}
StuService
6、Java实体类:Student
package com.test.excel.poi.entity; /**
* @author Javen
* @Email zyw205@gmail.com
*
*/
public class Student{
private int id;
private String name;
private String sex;
private int num; public Student() {
}
public Student(int id, String name, String sex, int num) {
this.id = id;
this.name = name;
this.sex = sex;
this.num = num;
} @Override
public String toString() {
return "StuEntity [id=" + id + ", name=" + name + ", sex=" + sex
+ ", num=" + num + "]";
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
} }
Student
excel2003和excel2007文件的创建和读取的更多相关文章
- VB高效导入Excel2003和Excel2007文件到MSHFlexGrid控件显示
1.VB高效导入Excel2003和Excel2007文件到MSHFlexGrid控件显示 2.以前也有Excel导入通用功能,但速度有些慢一会把两种实现方式都提供出为参考对比. 一.原通用导入exc ...
- 《python核心编程》笔记——文件的创建、读取和显示
创建文件(makeTextFile.py)脚本提醒用户输入一个尚不存在的文件名,然后由用户输入文件每一行,最后将所有文本写入文本文件 #!/usr/bin/env python 'makeTextFi ...
- jsp中excel文件的创建与读取
1.创建excel文件//这里的jxl不是java的标准jar包,需要在项目中另外加载 import jxl.Workbook; import jxl.write.Label; import jxl. ...
- 文件的创建,读取,写入,修改,删除---python入门
转自:http://blog.163.com/jackylau_v/blog/static/175754040201181505158356/ 一.用Python创建一个新文件,内容是从0到9的整数, ...
- 【小白学PyTorch】17 TFrec文件的创建与读取
[新闻]:机器学习炼丹术的粉丝的人工智能交流群已经建立,目前有目标检测.医学图像.时间序列等多个目标为技术学习的分群和水群唠嗑的总群,欢迎大家加炼丹兄为好友,加入炼丹协会.微信:cyx64501661 ...
- Halcon对文件的创建、读取、写入、删除等操作总结
Halcon可以操作普通文本文件,也可以操作二进制文件.如下图所示,只需要设置“FileType”参数的取值即可明确是操作文本文件还是二进制文件: 下面的程序是操作一个.txt文本文件的完整代码: * ...
- 【.NET深呼吸】Zip文件操作(1):创建和读取zip文档
.net的IO操作支持对zip文件的创建.读写和更新.使用起来也比较简单,.net的一向作风,东西都准备好了,至于如何使用,请看着办. 要对zip文件进行操作,主要用到以下三个类: 1.ZipFile ...
- 用 C# 轻松读取、改变文件的创建、修改、访问时间
创建时间是文件存入到电脑中的时间,而修改时间则是改变起内容的最后时间 // 读取文件的创建.修改.访问时间FileInfo fi = new FileInfo("C://test.txt&q ...
- 将excel2003文档文件转换为excel2007格式
在sharepoint 2010 中,excel2007或excel 2010文档格式,支持web app 应用,能够在浏览器在线打开,查看,但excel 2003格式的文档只能用office客户端打 ...
随机推荐
- 【CJOJ2482】【POI2000】促销活动
题面 Description 促销活动遵守以下规则: 一个消费者 -- 想参加促销活动的消费者,在账单下记下他自己所付的费用,他个人的详细情况,然后将账单放入一个特殊的投票箱. 当每天促销活动结束时, ...
- 解决Android Studio 3.0导入module依赖后unable to merge index
解决Android Studio 3.0导入module依赖后unable to merge index 项目需要使用im, 在项目里导入了腾讯im的几个module依赖, 项目无法编译, 报错una ...
- mycat操作MySQL第一篇:全局表
1.安装mycat,点击bin下面startup_nowrap.bat启动 2.客户端连接mycat:server.xml里面的 <!--连接mycat用户名和密码.数据库--> < ...
- Promise,我们来实战
Promise的基础我就不说了,我更加关心的是Promise能带给我什么便利?这也是本文的内容所在. Promise.all 并发执行多个异步方法,统一返回结果,结果按照参数的顺序返回. const ...
- 使用Angular CLI生成 Angular 5项目
如果您正在使用angular, 但是没有好好利用angular cli的话, 那么可以看看本文. Angular CLI 官网: https://github.com/angular/angular- ...
- [转]svn diff 替代工具
svn diff 替代工具 http://blog.csdn.net/fudesign2008/article/details/8168811 一. 使用vimdiff替换svn diff: 对于多数 ...
- 集群session管理问题
转自:http://book.51cto.com/art/201405/439557.htm 先来看一下什么是Session. 用户使用网站的服务,基本上需要浏览器与Web 服务器的多次交互.HTTP ...
- HashSet源码分析
在java集合中有一种集合Set(集),他有两个实现类,分别是HashSet,TreeSet.下面仔细分析HashSet源码. 看了HashSet的源码就会发现HashSet的底层实现是利用HashM ...
- Codeforces Round #471 (Div. 2) C. Sad powers
首先可以前缀和 ans = solve(R) - solve(L-1) 对于solve(x) 1-x当中符合条件的数 分两种情况 3,5,7,9次方的数,注意这地方不能含有平方次 平方数 #inclu ...
- day1 安装jdk8环境及第一个java程序
安装jdk8 第一步:下载jdk安装包,我们这里下载orical官网的jdk8版本.