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客户端打 ...
随机推荐
- [Luogu3527][POI2011]MET-Meteors
BZOJ权限题!提供洛谷链接! sol 昨晚突发奇想去学了一下整体二分. 这道题应该算是整体二分的板子题吧. 整体二分 首先要求可离线,不然还是安心码数据结构吧. 整体二分简单的来讲,就是时间复杂度可 ...
- Java中关于nextInt()、next()和nextLine()的理解
先看解释: nextInt(): it only reads the int value, nextInt() places the cursor in the same line after rea ...
- HUD-1999-不可摸数
参考博客https://www.cnblogs.com/dongsheng/archive/2012/08/18/2645594.html Problem Description s(n)是正整数n的 ...
- 异步解决方案promise及源码实现
js语言的特性,造就了特别的异步处理方式,我记得以前用的最多的就是回调函数,那个时候写jquery的ajax时候,特别喜欢写这种代码: $.ajax({ method:'get', url:" ...
- MSIL实用指南-加载null、string、long、float、double等值
本篇讲述怎么加载null.string值.long值.float值.double值. 加载null不需要参数值,只要 Emit ldnull 其它几个命令要 Emit <指令> <值 ...
- 关于jstl的使用
1.jsp中el表达式无法被解析 使用jstl标签的时候,发现el表达式无法被解析,后来查阅资料发现jsp中需要添加<%@page isELIgnored="false" % ...
- 为eclipse安装subclipse(SVN插件)
1.打开eclipse,点击菜单Help->Install New Software 2.进入安装窗体后,点击安装窗体的右侧的Add按钮,然后在弹出的窗体中输入名称:Subclipse 1.12 ...
- Android开发——签名包的生成
前言: 最近想要在酷安网上传apk,注册开发者的时候需要申请验证,验证需要两个apk,一个是自己的apk(需要签名),另外一个则是下载酷安的模板生成的一个签名包(使用的签名要与之前的签名自己的apk一 ...
- Asp.Net MVC 实现将Easy-UI展示数据下载为Excel 文件
在一个项目中,需要做一个将Easy-UI界面展示数据下载为Excel文件的功能,经过一段时间努力,完成了一个小Demo.界面如下: 但按下导出Excel后,Excel文件将会下载到本地,在office ...
- delphi简单的分页实现(高手可以不看)
适合初学者,练习几个控件的使用 1.先放一张界面控件布局: 4个button,2个label,1个edit,1个TRzsplitter(把界面分割成上下2部分),1一个adoquery,1个adoco ...