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客户端打 ...
随机推荐
- 杜教筛:Bzoj3944: sum
题意 求\(\sum_{i=1}^{n}\varphi(i)和\sum_{i=1}^{n}\mu(i)\) \(n <= 2^{31}-1\) 不会做啊... 只会线性筛,显然不能线性筛 这个时 ...
- 关于jstl的使用
1.jsp中el表达式无法被解析 使用jstl标签的时候,发现el表达式无法被解析,后来查阅资料发现jsp中需要添加<%@page isELIgnored="false" % ...
- body里面的onload和window.onload的区别
区别:body里面的onload是在“页面加载完成后执行的动作” window里面的onload是在“页面加载时执行的动作” 例子:在html页面中有一个大图片,想要在图片显示出来后提示一个消息框“图 ...
- Infinite Fraction Path HDU 6223 2017沈阳区域赛G题题解
题意:给你一个字符串s,找到满足条件(s[i]的下一个字符是s[(i*i+1)%n])的最大字典序的长度为n的串. 思路:类似后缀数组,每次倍增来对以i开头的字符串排序,复杂度O(nlogn).代码很 ...
- shell脚本中文件测试
shell脚本中文件测试 author:headsen chen 2017-10-17 14:35:19 个人原创,转载请注明作者,否则 依法追究法律责任 [ -f filename ] ...
- HTML定位简介
转载出处 定位一直是WEB标准应用中的难点,如果理不清楚定位那么可能应实现的效果实现不了,实现了的效果可能会走样.如果理清了定位的原理,那定位会让网页实现的更加完美. 定位的定义:在CSS中关于定位的 ...
- React 系列文章(1): npm 手动搭建React 运行实例 (新手必看)
摘 要 刚接触React 开发, 在摸索中构建react 运行环境,总会遇到各种坑:本文,将用最短时间解决webpack+react 环境搭建问题. 1.如果你还没有React基础 看这里. 2.如果 ...
- POJ-1032-拆数字
Description New convocation of The Fool Land's Parliament consists of N delegates. According to the ...
- redis-cli的一些有趣也很有用的功能
redis-cli我们最常用的两个参数就是-h.-p.-a选项,分配用来指定连接的redis-server的host和port. 通过redis-cli –help发现,redis-cli还提供了其他 ...
- 单例模式双重检验锁的判断是否为null的意义
关于双重检验锁首先简单来看一个小例子: public class Singleton{ private static Singleton instance = null; private Single ...