怎样在java中导出xls文件

Python09

怎样在java中导出xls文件,第1张

通过这个例子,演示以下如何用java生成excel文件

import org.apache.poi.hssf.usermodel.*

import java.io.FileOutputStream

import java.io.IOException

publicclass CreateCells

{

publicstaticvoid main(String[] args)

throws IOException

{

HSSFWorkbook wb = new HSSFWorkbook()//建立新HSSFWorkbook对象

HSSFSheet sheet = wb.createSheet("new sheet")//建立新的sheet对象

// Create a row and put some cells in it. Rows are 0 based.

HSSFRow row = sheet.createRow((short)0)//建立新行

// Create a cell and put a value in it.

HSSFCell cell = row.createCell((short)0)//建立新cell

cell.setCellValue(1)//设置cell的整数类型的值

// Or do it on one line.

row.createCell((short)1).setCellValue(1.2)//设置cell浮点类型的值

row.createCell((short)2).setCellValue("test")//设置cell字符类型的值

row.createCell((short)3).setCellValue(true)//设置cell布尔类型的值

HSSFCellStyle cellStyle = wb.createCellStyle()//建立新的cell样式

cellStyle.setDataFormat(HSSFDataFormat.getFormat("m/d/yy h:mm"))//设置cell样式为定制的日期格式

HSSFCell dCell =row.createCell((short)4)

dCell.setCellValue(new Date())//设置cell为日期类型的值

dCell.setCellStyle(cellStyle)//设置该cell日期的显示格式

HSSFCell csCell =row.createCell((short)5)

csCell.setEncoding(HSSFCell.ENCODING_UTF_16)//设置cell编码解决中文高位字节截断

csCell.setCellValue("中文测试_Chinese Words Test")//设置中西文结合字符串

row.createCell((short)6).setCellType(HSSFCell.CELL_TYPE_ERROR)//建立错误cell

// Write the output to a file

FileOutputStream fileOut = new FileOutputStream("workbook.xls")

wb.write(fileOut)

fileOut.close()

}

}

从以上例子,可以清楚的看到xls文件从大到小包扩了 HSSFWorkbook HSSFSheet HSSFRow HSSFCell这样几个对象。还可以在cell中设置各种类型的值。尤其要注意的是如果你想正确的显示非欧美的字符时,尤其象中日韩这样的语言,必须 设置编码为16位的即是HSSFCell.ENCODING_UTF_16,才能保证字符的高8位不被截断而引起编码失真形成乱码。

其他测试可以通过参考examples包中的测试例子掌握poi的详细用法,包括字体的设置,cell大小和低纹的设置等。需要注意的是POI是一 个仍然在完善中的公开代码的项目,所以有些功能正在不断的扩充。如HSSFSheet的getFooter() getHeader()和 setFooter(HSSFFooter hsf) setHeader(HSSFHeader hsh)是在POI1.7中才有的,而POI1.5中就没有。运行测试熟悉代码或者使用它做项目时请注意POI的版本。

另外需要注意的是HSSF也有它的对xls基于事件的解析。可以参考例程中的EventExample.java。它通过实现 HSSFListener完成从普通流认知Xls中包含的内容,在apache Cocoon中的 org.apache.cocoon.serialization.HSSFSerializer中用到了这个解析。因为Cocoon2 是基于事件的,所以POI为了提供快速的解析也提供了相应的事件。当然我们自己也可以实现这个事件接口。

因为POI还不是一个足够成熟的项目,所以有必要做进一步的开发和测试。但是它已经为我们用纯java操作ole2对象提供了可能,而且克服了ole对象调用的缺陷,提供了服务器端的Excel解决方案。

利用Java 创建和读取Excel文档

为了保证示例程序的运行,必须安装Java 2 sdk1.4.0 和Jakarta POI,Jakarta POI的Web站点是: http://jakarta.apache.org/poi/

示例1将演示如何利用Jakarta POI API 创建Excel 文档。

示例1程序如下:

import org.apache.poi.hssf.usermodel.HSSFWorkbook

import org.apache.poi.hssf.usermodel.HSSFSheet

import org.apache.poi.hssf.usermodel.HSSFRow

import org.apache.poi.hssf.usermodel.HSSFCell

import java.io.FileOutputStream

publicclass CreateXL {

/** Excel 文件要存放的位置,假定在D盘JTest目录下*/

publicstatic String outputFile="D:/JTest/ gongye.xls"

publicstaticvoid main(String argv[])

{

try

{

// 创建新的Excel 工作簿

HSSFWorkbook workbook = new HSSFWorkbook()

// 在Excel工作簿中建一工作表,其名为缺省值

// 如要新建一名为"效益指标"的工作表,其语句为:

// HSSFSheet sheet = workbook.createSheet("效益指标")

HSSFSheet sheet = workbook.createSheet()

// 在索引0的位置创建行(最顶端的行)

HSSFRow row = sheet.createRow((short)0)

//在索引0的位置创建单元格(左上端)

HSSFCell cell = row.createCell((short) 0)

// 定义单元格为字符串类型

cell.setCellType(HSSFCell.CELL_TYPE_STRING)

// 在单元格中输入一些内容

cell.setCellValue("增加值")

// 新建一输出文件流

FileOutputStream fOut = new FileOutputStream(outputFile)

// 把相应的Excel 工作簿存盘

workbook.write(fOut)

fOut.flush()

// 操作结束,关闭文件

fOut.close()

System.out.println("文件生成...")

}catch(Exception e) {

System.out.println("已运行 xlCreate() : " + e )

}

}

}

这里演示创建和设置字体和单元格的格式,然后再应用这些格式:

1、创建字体,设置其为红色、粗体:

HSSFFont font = workbook.createFont()

font.setColor(HSSFFont.COLOR_RED)

font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD)

2、创建格式

HSSFCellStyle cellStyle= workbook.createCellStyle()

cellStyle.setFont(font)

3、应用格式

HSSFCell cell = row.createCell((short) 0)

cell.setCellStyle(cellStyle)

cell.setCellType(HSSFCell.CELL_TYPE_STRING)

cell.setCellValue("标题 ")

总之,如本篇文章所演示的一样,Java程序员不必担心Excel工作表中的数据了,利用Jakarta POI API, 就可以轻易的在程序中存取Excel文档。

可以使用POI开源的api:

1.首先下载poi-3.6-20091214.jar,下载地址如下:

http://download.csdn.net/detail/evangel_z/3895051

2.Student.java

import java.util.Date

public class Student

{

private int id

private String name

private int age

private Date birth

public Student()

{

}

public Student(int id, String name, int age, Date birth)

{

this.id = id

this.name = name

this.age = age

this.birth = birth

}

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 int getAge()

{

return age

}

public void setAge(int age)

{

this.age = age

}

public Date getBirth()

{

return birth

}

public void setBirth(Date birth)

{

this.birth = birth

}

}

3.CreateSimpleExcelToDisk.java

import java.io.FileOutputStream

import java.text.SimpleDateFormat

import java.util.ArrayList

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

public class CreateSimpleExcelToDisk

{

/**

* @功能:手工构建一个简单格式的Excel

*/

private static List<Student>getStudent() throws Exception

{

List list = new ArrayList()

SimpleDateFormat df = new SimpleDateFormat("yyyy-mm-dd")

Student user1 = new Student(1, "张三", 16, df.parse("1997-03-12"))

Student user2 = new Student(2, "李四", 17, df.parse("1996-08-12"))

Student user3 = new Student(3, "王五", 26, df.parse("1985-11-12"))

list.add(user1)

list.add(user2)

list.add(user3)

return list

}

public static void main(String[] args) throws Exception

{

// 第一步,创建一个webbook,对应一个Excel文件

HSSFWorkbook wb = new HSSFWorkbook()

// 第二步,在webbook中添加一个sheet,对应Excel文件中的sheet

HSSFSheet sheet = wb.createSheet("学生表一")

// 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short

HSSFRow row = sheet.createRow((int) 0)

// 第四步,创建单元格,并设置值表头 设置表头居中

HSSFCellStyle style = wb.createCellStyle()

style.setAlignment(HSSFCellStyle.ALIGN_CENTER)// 创建一个居中格式

HSSFCell cell = row.createCell((short) 0)

cell.setCellValue("学号")

cell.setCellStyle(style)

cell = row.createCell((short) 1)

cell.setCellValue("姓名")

cell.setCellStyle(style)

cell = row.createCell((short) 2)

cell.setCellValue("年龄")

cell.setCellStyle(style)

cell = row.createCell((short) 3)

cell.setCellValue("生日")

cell.setCellStyle(style)

// 第五步,写入实体数据 实际应用中这些数据从数据库得到,

List list = CreateSimpleExcelToDisk.getStudent()

for (int i = 0i <list.size()i++)

{

row = sheet.createRow((int) i + 1)

Student stu = (Student) list.get(i)

// 第四步,创建单元格,并设置值

row.createCell((short) 0).setCellValue((double) stu.getId())

row.createCell((short) 1).setCellValue(stu.getName())

row.createCell((short) 2).setCellValue((double) stu.getAge())

cell = row.createCell((short) 3)

cell.setCellValue(new SimpleDateFormat("yyyy-mm-dd").format(stu

.getBirth()))

}

// 第六步,将文件存到指定位置

try

{

FileOutputStream fout = new FileOutputStream("E:/students.xls")

wb.write(fout)

fout.close()

}

catch (Exception e)

{

e.printStackTrace()

}

}

}