* @author liuwu
* Excel的导入与导出
*/
@SuppressWarnings({ "unchecked" })
public class ExcelOperate {
/**
* @author liuwu
* 这是一个通用的方法,利用了JAVA的反射机制,
* 可以将放置在JAVA集合中并且符合一定条件的数据以EXCEL的形式输出到指定IO设备上
* @param title 表格标题名
* @param headers 表格属性列名数组
* @param dataset 需要显示的数据集合,集合中一定要放置符合javabean风格的类的对象。
* 此方法支持的 javabean属性【数据类型有java基本数据类型及String,Date,byte[](图片转成字节码)】
* @param out 与输出设备关联的流对象,可以将EXCEL文档导出到本地文件或者网络中
* @param pattern 如果有时间数据,设定输出格式。默认为"yyy-MM-dd"
* @throws IOException
*/
public static void exportExcel(String title, String[] headers,Collection<?> dataset, OutputStream out, String pattern) throws IOException {
// 声明一个工作薄
HSSFWorkbook workbook = new HSSFWorkbook()
// 生成一个表格
HSSFSheet sheet = workbook.createSheet(title)
// 设置表格默认列宽度为15个字节
sheet.setDefaultColumnWidth((short) 20)
// 生成一个样式
HSSFCellStyle style = workbook.createCellStyle()
// 设置这些样式
style.setFillForegroundColor(HSSFColor.SKY_BLUE.index)
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND)
style.setBorderBottom(HSSFCellStyle.BORDER_THIN)
style.setBorderLeft(HSSFCellStyle.BORDER_THIN)
style.setBorderRight(HSSFCellStyle.BORDER_THIN)
style.setBorderTop(HSSFCellStyle.BORDER_THIN)
style.setAlignment(HSSFCellStyle.ALIGN_CENTER)
// 生成一个字体
HSSFFont font = workbook.createFont()
font.setColor(HSSFColor.VIOLET.index)
font.setFontHeightInPoints((short) 12)
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD)
// 把字体应用到当前的样式
style.setFont(font)
// 生成并设置另一个样式
HSSFCellStyle style2 = workbook.createCellStyle()
style2.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index)
style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND)
style2.setBorderBottom(HSSFCellStyle.BORDER_THIN)
style2.setBorderLeft(HSSFCellStyle.BORDER_THIN)
style2.setBorderRight(HSSFCellStyle.BORDER_THIN)
style2.setBorderTop(HSSFCellStyle.BORDER_THIN)
style2.setAlignment(HSSFCellStyle.ALIGN_CENTER)
style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER)
// 生成另一个字体
HSSFFont font2 = workbook.createFont()
font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL)
// 把字体应用到当前的样式
style2.setFont(font2)
// 产生表格标题行
HSSFRow row = sheet.createRow(0)
for (short i = 0 i < headers.length i++) {
HSSFCell cell = row.createCell(i)
cell.setCellStyle(style)
HSSFRichTextString text = new HSSFRichTextString(headers[i])
cell.setCellValue(text)
}
// 遍历集合数据,产生数据行
Iterator<?> it = dataset.iterator()
int index = 0
while (it.hasNext()) {
index++
row = sheet.createRow(index)
Object t = it.next()
// 利用反射,根据javabean属性的先后顺序,动态调用getXxx()方法得到属性值
Field[] fields = t.getClass().getDeclaredFields()
for (short i = 0 i < fields.length i++) {
HSSFCell cell = row.createCell(i)
cell.setCellStyle(style2)
Field field = fields[i]
String fieldName = field.getName()
String getMethodName = "get"
+ fieldName.substring(0, 1).toUpperCase()
+ fieldName.substring(1)//注意 实体get Set不要自己改名字不然反射会有问题
try {
Class tCls = t.getClass()
Method getMethod = tCls.getMethod(getMethodName,new Class[] {})
Object value = getMethod.invoke(t, new Object[] {})
HSSFRichTextString richString = new HSSFRichTextString(value.toString())
HSSFFont font3 = workbook.createFont()
font3.setColor(HSSFColor.BLUE.index)
richString.applyFont(font3)
cell.setCellValue(richString)
} catch (SecurityException e) {
e.printStackTrace()
e=null
} catch (NoSuchMethodException e) {
e.printStackTrace()
e=null
} catch (IllegalArgumentException e) {
e.printStackTrace()
e=null
} catch (IllegalAccessException e) {
e.printStackTrace()
e=null
} catch (InvocationTargetException e) {
e.printStackTrace()
e=null
} finally {
// 清理资源
}
}
}
try {
workbook.write(out)
} catch (IOException e) {
e.printStackTrace()
e=null
}
}
}
//java生成简单的Excel文件package beans.excel
import java.io.IOException
import java.io.OutputStream
import jxl.Workbook
import jxl.write.Label
import jxl.write.WritableSheet
import jxl.write.WritableWorkbook
import jxl.write.WriteException
public class SimpleExcelWrite {
public void createExcel(OutputStream os) throws WriteException,IOException{
//创建工作薄
WritableWorkbook workbook = Workbook.createWorkbook(os)
//创建新的一页
WritableSheet sheet = workbook.createSheet("First Sheet",0)
//创建要显示的内容,创建一个单元格,第一个参数为列坐标,第二个参数为行坐标,第三个参数为内容
Label xuexiao = new Label(0,0,"学校")
sheet.addCell(xuexiao)
Label zhuanye = new Label(1,0,"专业")
sheet.addCell(zhuanye)
Label jingzhengli = new Label(2,0,"专业竞争力")
sheet.addCell(jingzhengli)
Label qinghua = new Label(0,1,"清华大学")
sheet.addCell(qinghua)
Label jisuanji = new Label(1,1,"计算机专业")
sheet.addCell(jisuanji)
Label gao = new Label(2,1,"高")
sheet.addCell(gao)
Label beida = new Label(0,2,"北京大学")
sheet.addCell(beida)
Label falv = new Label(1,2,"法律专业")
sheet.addCell(falv)
Label zhong = new Label(2,2,"中")
sheet.addCell(zhong)
Label ligong = new Label(0,3,"北京理工大学")
sheet.addCell(ligong)
Label hangkong = new Label(1,3,"航空专业")
sheet.addCell(hangkong)
Label di = new Label(2,3,"低")
sheet.addCell(di)
//把创建的内容写入到输出流中,并关闭输出流
workbook.write()
workbook.close()
os.close()
}
}
可以使用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()
}
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)