本文目录一览:
- 1、java代码怎么导出excel文件
- 2、java如何另存导出Excel
- 3、java怎么导出excel表格
- 4、java怎样输出excel文件
- 5、java导出数据到excel的几种方法的比较
- 6、怎么用java实现导出excel
java代码怎么导出excel文件
excel工具类
package com.ohd.ie.product.action;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import org.apache.commons.io.output.ByteArrayOutputStream;
import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.VerticalAlignment;
import jxl.write.*;
import jxl.write.Number;
import jxl.write.biff.RowsExceededException;
public class Excel {
private OutputStream os;
private WritableWorkbook wwb = null;
private WritableSheet ws = null;
private WritableCellFormat titleCellFormat = null;
private WritableCellFormat noBorderCellFormat = null;
private WritableCellFormat hasBorderCellFormat = null;
private WritableCellFormat hasBorderCellNumberFormat = null;
private WritableCellFormat hasBorderCellNumberFormat2 = null;
private WritableImage writableImage=null;
private int r;
public Excel(OutputStream os){
this.os = os;
r = -1;
try {
wwb = Workbook.createWorkbook(os);
//创建工作表
ws = wwb.createSheet("sheet1",0);
//设置表头字体,大小,加粗
titleCellFormat = new WritableCellFormat();
titleCellFormat.setAlignment(Alignment.CENTRE);
titleCellFormat.setVerticalAlignment(VerticalAlignment.CENTRE);
//自动换行
titleCellFormat.setWrap(true);
titleCellFormat.setFont(new WritableFont(WritableFont.createFont("宋体"),12,WritableFont.BOLD));
titleCellFormat.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);
//设置表格字体,大小----无边框
noBorderCellFormat = new WritableCellFormat();
noBorderCellFormat.setAlignment(Alignment.CENTRE);
noBorderCellFormat.setVerticalAlignment(VerticalAlignment.CENTRE);
noBorderCellFormat.setFont(new WritableFont(WritableFont.createFont("宋体"),12));
//设置表格字体,大小----有边框
hasBorderCellFormat = new WritableCellFormat();
hasBorderCellFormat.setAlignment(Alignment.CENTRE);
hasBorderCellFormat.setVerticalAlignment(VerticalAlignment.CENTRE);
hasBorderCellFormat.setFont(new WritableFont(WritableFont.createFont("宋体"),12));
hasBorderCellFormat.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);
//设置表格字体,大小----有边框(小数)
NumberFormat nf = new NumberFormat("#0.00");
hasBorderCellNumberFormat = new WritableCellFormat(nf);
hasBorderCellNumberFormat.setAlignment(Alignment.CENTRE);
hasBorderCellNumberFormat.setVerticalAlignment(VerticalAlignment.CENTRE);
hasBorderCellNumberFormat.setFont(new WritableFont(WritableFont.createFont("宋体"),12));
hasBorderCellNumberFormat.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);
//设置表格字体,大小----有边框(整数)
NumberFormat nf2 = new NumberFormat("#0");
hasBorderCellNumberFormat2 = new WritableCellFormat(nf2);
hasBorderCellNumberFormat2.setAlignment(Alignment.CENTRE);
hasBorderCellNumberFormat2.setVerticalAlignment(VerticalAlignment.CENTRE);
hasBorderCellNumberFormat2.setFont(new WritableFont(WritableFont.createFont("宋体"),12));
hasBorderCellNumberFormat2.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
*
* @param content 内容
* @param c 列
* @param style 样式
* @param isNewLine 是否换行
* @param mergeType 合并类型
* @param mergeCount 合并个数
* @param width 单元格宽
*/
public void setExcelCell(String content,int c,int style,boolean isNewLine,int mergeType,int mergeCount,int width){
try {
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////报表内容////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
if(isNewLine){
r++;
}
WritableCell l = null;
if(style == 1){
l = new Label(c,r,content,titleCellFormat);
}
else if(style == 2){
l = new Label(c,r,content,noBorderCellFormat);
}
else if(style == 3){
l = new Label(c,r,content,hasBorderCellFormat);
}
else if(style == 4){
l = new Number(c,r,Double.parseDouble(content),hasBorderCellNumberFormat);
}
else if(style == 5){
l = new Number(c,r,Integer.parseInt(content),hasBorderCellNumberFormat2);
}
ws.addCell(l);
if(width != 0){
ws.setColumnView(c,width);
}
//veryhuo,com
if(mergeType == 1){
//x 轴方向
ws.mergeCells(c, r, c+mergeCount-1 , r);
}
else if(mergeType == 2){
//y 轴方向
ws.mergeCells(c, r, c, r+mergeCount-1);
}
if(isNewLine){
ws.setRowView(r, 350);
if(style == 1 r != 0){
ws.setRowView(r, 900);
}
else{
ws.setRowView(r, 350);
}
}
//
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
} catch (Exception e) {
System.out.println(e.toString());
}
}
public void setExcelCellEx(String content,int c,int style,boolean isNewLine,int mergeType,int mergeCount,int width,int row){
try {
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////报表内容////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
if(isNewLine){
r++;
}
WritableCell l = null;
if(style == 1){
l = new Label(c,r,content,titleCellFormat);
}
else if(style == 2){
l = new Label(c,r,content,noBorderCellFormat);
}
else if(style == 3){
if(content.indexOf(".jpg")!=-1 ||content.indexOf(".JPG")!=-1){
File outputFile=null;
File imgFile =new File(content);
if(imgFile.exists()imgFile.length()0){
BufferedImage input=null;
try {
input = ImageIO.read(imgFile);
} catch (Exception e) {
e.printStackTrace();
}
if(input!=null){
String path=imgFile.getAbsolutePath();
outputFile = new File(path.substring(0,path.lastIndexOf('.')+1)+"png");
ImageIO.write(input, "PNG", outputFile);
if(outputFile.exists()outputFile.length()0){
ws.setRowView(row,2000);
//ws.setColumnView(8, 10);
writableImage = new WritableImage(c+0.1, row+0.1, 0.8, 0.8, outputFile);
ws.addImage(writableImage);
l = new Label(c,r,"",hasBorderCellFormat);
}
}
}
}else{
l = new Label(c,r,content,hasBorderCellFormat);
}
}
else if(style == 4){
l = new Number(c,r,Double.parseDouble(content),hasBorderCellNumberFormat);
}
else if(style == 5){
l = new Number(c,r,Integer.parseInt(content),hasBorderCellNumberFormat2);
}
ws.addCell(l);
if(width != 0){
ws.setColumnView(c,width);
}
if(mergeType == 1){
//x 轴方向
ws.mergeCells(c, r, c+mergeCount-1 , r);
}
else if(mergeType == 2){
//y 轴方向
ws.mergeCells(c, r, c, r+mergeCount-1);
}
if(isNewLine){
ws.setRowView(r, 350);
if(style == 1 r != 0){
ws.setRowView(r, 900);
}
else{
ws.setRowView(r, 350);
}
}
} catch (Exception e) {
System.out.println(e.toString());
}
}
public void setRowHeight(int val){
try {
ws.setRowView(r, val);
} catch (RowsExceededException e) {
e.printStackTrace();
}
}
public void getExcelResult(){
try {
wwb.write();
} catch (Exception e) {
System.out.println(e.toString());
}
finally{
if(wwb != null){
try {
wwb.close();
if(os != null){
os.close();
}
} catch (WriteException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
需要的jar包:jxl.jar
java如何另存导出Excel
1./**
* 出险信息导出到excel(fc)
* @param mapping
* @param form
* @param request
* @param response
* @throws IOException
*/
public void exportActoExcel(ActionMapping mapping, ActionForm form ,
HttpServletRequest request,HttpServletResponse response) throws IOException {
ActionErrors errors = new ActionErrors();
AcExcelBusi acBusi = new AcExcelBusi();
AccidentRecordForm arForm= (AccidentRecordForm) form;
AccidentRecordBusi arBusi = new AccidentRecordBusi();
// ////查询条件
FwUsers sessUser = (FwUsers)request.getSession().getAttribute(ConstValues.SESS_USER_MANAGE);
MapString,Object cisMap = arBusi.getTodoPageList(arForm,sessUser,errors);
List AcList = null;// 当页的记录
if (null != cisMap) {
AcList = (List) cisMap.get("list");
}
//导出excel的路径、文件名
String uuid = UUID.create("exp");
String path = request.getSession().getServletContext().getRealPath("/") + ConstValues.EXP_PATH_EXCEL + uuid + ".xls";
acBusi.exprotAcExcel(AcList, path,request);
response.sendRedirect("stdownload.jsp?path=" + path );
}
2./**
* 导出出险信息 fc
*
* @param jzForm
* 查询条件
* @param sessionUser
* 当前登录session用户
* @param errors
* Action错误
* @return
*/
public void exprotAcExcel(List list, String path,HttpServletRequest request) {
try {
WritableWorkbook workbook = Workbook.createWorkbook(new File(path));// 创建工作簿(filePos为excel文件的路径)
WritableSheet sheet = workbook.createSheet("出险信息", 0);// 创建工作页
// 内容(居中)单元格样式
WritableCellFormat contentStyle = new WritableCellFormat(); //
contentStyle.setAlignment(jxl.format.Alignment.CENTRE); // 设置对齐方式
contentStyle.setBorder(jxl.format.Border.ALL,
jxl.format.BorderLineStyle.THIN); // 设置边框
// 一级标题单元格样式
WritableFont wf1 = new WritableFont(WritableFont.ARIAL, 15,
WritableFont.BOLD, false); // 定义格式 字体 下划线 斜体 粗体 颜色
WritableCellFormat titleStyle1 = new WritableCellFormat(wf1); //
titleStyle1.setBackground(jxl.format.Colour.GREEN); // 设置单元格的背景颜色
titleStyle1.setAlignment(jxl.format.Alignment.CENTRE); // 设置对齐方式
titleStyle1.setBorder(jxl.format.Border.ALL,
jxl.format.BorderLineStyle.THIN); // 设置边框
// 二级标题单元格样式
WritableFont wf2 = new WritableFont(WritableFont.ARIAL, 11,
WritableFont.BOLD, false); // 定义格式 字体 下划线 斜体 粗体 颜色
WritableCellFormat titleStyle2 = new WritableCellFormat(wf2); //
titleStyle2.setBackground(jxl.format.Colour.GREY_25_PERCENT); // 设置单元格的背景颜色
titleStyle2.setAlignment(jxl.format.Alignment.CENTRE); // 设置水平对齐方式
titleStyle2
.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE); // 设置垂直对齐方式
titleStyle2.setBorder(jxl.format.Border.ALL,
jxl.format.BorderLineStyle.THIN); // 设置边框
WritableCellFormat titleStyle3 = new WritableCellFormat(wf1); //
titleStyle3.setBackground(jxl.format.Colour.BRIGHT_GREEN); // 设置单元格的背景颜色
titleStyle3.setAlignment(jxl.format.Alignment.CENTRE); // 设置对齐方式
titleStyle3.setBorder(jxl.format.Border.ALL,
jxl.format.BorderLineStyle.THIN); // 设置边框
// 设置冻结单元格
sheet.getSettings().setVerticalFreeze(2);
sheet.getSettings().setHorizontalFreeze(5);
sheet.setColumnView(0, 8); // 设置列的宽度
sheet.setColumnView(1, 10); // 设置列的宽度
sheet.setRowView(0, 0);
sheet.addCell(new Label(0, 0, "hysj5800294*#", titleStyle1));// 标题
sheet.addCell(new Label(0, 1, "出险信息 ", titleStyle2));// 标题
sheet.mergeCells(0, 2, 33, 2); // 合并单元格
sheet.addCell(new Label(0, 2, "出险信息 ", titleStyle1));// 标题
sheet.addCell(new Label(0, 3, "序号", titleStyle2));// 往单元格中填写数据
sheet.addCell(new Label(1, 3, "省内/省外", titleStyle2));// 往单元格中填写数据
if (list != null list.size() 0) {
for (int i = 0; i list.size(); i++) {
sheet.setRowView(i + 3, 300); // 设置行高
//转换数据信息
//Object[] obj = (Object[]) list.get(i);
AccidentRecord ar = (AccidentRecord) list.get(i);
sheet.addCell(new Label(0, i + 4, String.valueOf(i + 1),contentStyle));// 往单元格中填写数据 序号
sheet.addCell(new Label(1, i + 4, ar.getLicenceProvince().toString(),contentStyle));// 省内/省外
}
}
workbook.write();// 书写到工作簿
workbook.close();// 关闭工作簿,输出完成
} catch (Exception e) {
e.printStackTrace();
}
}
}
3.功能可以实现,可以到处,点击下载确定。
4.打开已经下载的excel,如图显示结果。得到想要的结构。
java怎么导出excel表格
可以使用POI开源的api:
1.首先下载poi-3.6-20091214.jar,下载地址如下:
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 ListStudent 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 = 0; i 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();
}
}
}
java怎样输出excel文件
//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();
}
}
java导出数据到excel的几种方法的比较
Excel的两种导出入门方法(JAVA与JS)
最近在做一个小项目作为练手,其中使用到了导出到Excel表格,一开始做的是使用JAVA的POI导出的,但因为我的数据是爬虫爬出来的,数据暂时并不保存在数据库或后台,所以直接显示在HTML的table,需要下载时又要将数据传回后台然后生成Excel文件,最后再从服务器下载到本地,过程几度经过网络传输,感觉比较耗时与浪费性能,于是想着在HTML中的Table直接导到Excel中节约资源
JAVA导出EXCEL(.xls)
导出Excel用的插件是apache的poi.jar,maven地址如下
dependency
groupIdorg.apache.poi/groupId
artifactIdpoi/artifactId
version3.17/version/dependency
1. 简单应用
先来个简化无样式的Excel导出,由于我的数据存在JSON中,所以形参是JSONArray,朋友们根据自己的实际数据类型(Map,List,Set等)传入即可 ,代码如下
/**
* 创建excel并填入数据
* @author LiQuanhui
* @date 2017年11月24日 下午5:25:13
* @param head 数据头
* @param body 主体数据
* @return HSSFWorkbook
*/
public static HSSFWorkbook expExcel(JSONArray head, JSONArray body) { //创建一个excel工作簿
HSSFWorkbook workbook = new HSSFWorkbook(); //创建一个sheet工作表
HSSFSheet sheet = workbook.createSheet("学生信息");
//创建第0行表头,再在这行里在创建单元格,并赋值
HSSFRow row = sheet.createRow(0);
HSSFCell cell = null; for (int i = 0; i head.size(); i++) {
cell = row.createCell(i);
cell.setCellValue(head.getString(i));//设置值
}
//将主体数据填入Excel中
for (int i = 0, isize = body.size(); i isize; i++) {
row = sheet.createRow(i + 1);
JSONArray stuInfo = body.getJSONArray(i); for (int j = 0, jsize = stuInfo.size(); j jsize; j++) {
cell = row.createCell(j);
cell.setCellValue(stuInfo.getString(j));//设置值
}
} return workbook;
}
创建好Excel对象并填好值后(就是得到workbook),就是将这个对象以文件流的形式输出到本地上去,代码如下
/**
* 文件输出
* @author LiQuanhui
* @date 2017年11月24日 下午5:26:23
* @param workbook 填充好的workbook
* @param path 存放的位置
*/
public static void outFile(HSSFWorkbook workbook,String path) {
OutputStream os=null; try {
os = new FileOutputStream(new File(path));
workbook.write(os);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
至此Excel的导出其实已经做完了。
2. 添加样式后导出
但通常这并不能满足我们的需求,因为通常是需要设置Excel的一些样式的,如字体、居中等等,设置单元格样式主要用到这个类(HSSFCellStyle)
HSSFCellStyle cellStyle = workbook.createCellStyle();
现在说说HSSFCellStyle都能干些什么
HSSFCellStyle cellStyle = workbook.createCellStyle();//创建单元格样式对象1.设置字体
HSSFFont font = workbook.createFont(); //font.setFontHeight((short)12);//这个设置字体会很大
font.setFontHeightInPoints((short)12);//这才是我们平常在Excel设置字体的值
font.setFontName("黑体");//字体:宋体、华文行楷等等
cellStyle.setFont(font);//将该字体设置进去2.设置对齐方式
cellStyle.setAlignment(horizontalAlignment);//horizontalAlignment参考下面给出的参数
//以下是最常用的三种对齐分别是居中,居左,居右,其余的写代码的时候按提示工具查看即可
HorizontalAlignment.CENTER
HorizontalAlignment.LEFT
HorizontalAlignment.RIGHT3.设置边框
cellStyle.setBorderBottom(border); // 下边框
cellStyle.setBorderLeft(border);// 左边框
cellStyle.setBorderTop(border);// 上边框
cellStyle.setBorderRight(border);// 右边框
//border的常用参数如下
BorderStyle.NONE 无边框
BorderStyle.THIN 细边框
BorderStyle.MEDIUM 中等粗边框
BorderStyle.THICK 粗边框//其余的我也描述不清是什么形状,有兴趣的到时可以直接测试
在经过一系列的添加样式之后,最后就会给单元格设置样式
cell.setCellStyle(cellStyle);
3. 自动调整列宽
sheet.autoSizeColumn(i);//i为第几列,需要全文都单元格居中的话,需要遍历所有的列数
4. 完整的案例
public class ExcelUtils { /**
* 创建excel并填入数据
* @author LiQuanhui
* @date 2017年11月24日 下午5:25:13
* @param head 数据头
* @param body 主体数据
* @return HSSFWorkbook
*/
public static HSSFWorkbook expExcel(JSONArray head, JSONArray body) {
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("学生信息");
HSSFRow row = sheet.createRow(0);
HSSFCell cell = null;
HSSFCellStyle cellStyle = workbook.createCellStyle();
setBorderStyle(cellStyle, BorderStyle.THIN);
cellStyle.setFont(setFontStyle(workbook, "黑体", (short) 14));
cellStyle.setAlignment(HorizontalAlignment.CENTER);
for (int i = 0; i head.size(); i++) {
cell = row.createCell(i);
cell.setCellValue(head.getString(i));
cell.setCellStyle(cellStyle);
}
HSSFCellStyle cellStyle2 = workbook.createCellStyle();
setBorderStyle(cellStyle2, BorderStyle.THIN);
cellStyle2.setFont(setFontStyle(workbook, "宋体", (short) 12));
cellStyle2.setAlignment(HorizontalAlignment.CENTER); for (int i = 0, isize = body.size(); i isize; i++) {
row = sheet.createRow(i + 1);
JSONArray stuInfo = body.getJSONArray(i); for (int j = 0, jsize = stuInfo.size(); j jsize; j++) {
cell = row.createCell(j);
cell.setCellValue(stuInfo.getString(j));
cell.setCellStyle(cellStyle2);
}
} for (int i = 0, isize = head.size(); i isize; i++) {
sheet.autoSizeColumn(i);
} return workbook;
} /**
* 文件输出
* @author LiQuanhui
* @date 2017年11月24日 下午5:26:23
* @param workbook 填充好的workbook
* @param path 存放的位置
*/
public static void outFile(HSSFWorkbook workbook,String path) {
OutputStream os=null; try {
os = new FileOutputStream(new File(path));
workbook.write(os);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
} /**
* 设置字体样式
* @author LiQuanhui
* @date 2017年11月24日 下午3:27:03
* @param workbook 工作簿
* @param name 字体类型
* @param height 字体大小
* @return HSSFFont
*/
private static HSSFFont setFontStyle(HSSFWorkbook workbook, String name, short height) {
HSSFFont font = workbook.createFont();
font.setFontHeightInPoints(height);
font.setFontName(name); return font;
} /**
* 设置单元格样式
* @author LiQuanhui
* @date 2017年11月24日 下午3:26:24
* @param workbook 工作簿
* @param border border样式
*/
private static void setBorderStyle(HSSFCellStyle cellStyle, BorderStyle border) {
cellStyle.setBorderBottom(border); // 下边框
cellStyle.setBorderLeft(border);// 左边框
cellStyle.setBorderTop(border);// 上边框
cellStyle.setBorderRight(border);// 右边框
}
}
POI的功能其实还是很强大的,这里只介绍了Excel的一丁点皮毛给入门的查看,如果想对Excel进行更多的设置可以查看下面的这篇文章,有着大量的使用说明。
空谷幽澜的POI使用详解
JS导出EXCEL(.xls)
java的Excel导出提供了强大的功能,但也对服务器造成了一定资源消耗,若能使用客户端的资源那真是太好了
1. 简单应用
JS的导出Excel非常简单,只需要引用Jquery和tableExport.js并设置一个属性即可
script src="%=basePath%/static/js/tableExport.js" type="text/javascript"/scriptscript type="text/javascript"
function exportExcelWithJS(){ //获取要导出Excel的表格对象并设置tableExport方法,设置导出类型type为excel
$('#tableId').tableExport({ type:'excel'
});
}/scriptbutton class="btn btn-primary" type="button" style="float: right;" onclick="exportExcelWithJS()"下载本表格/button
JS的导出就完成了,是不是特别简单
2. 进阶应用
但上面仅仅是个简单的全表无样式的导出
这tableExport.js还有一些其他功能,忽略行,忽略列,设置样式等,属性如下
script type="text/javascript"
function exportExcelWithJS(){ //获取要导出Excel的表格对象并设置tableExport方法,设置导出类型type为excel
$('#tableId').tableExport({ type:'excel',//导出为excel
fileName:'2017工资表',//文件名
worksheetName:'11月工资',//sheet表的名字
ignoreColumn:[0,1,2],//忽略的列,从0开始算
ignoreRow:[2,4,5],//忽略的行,从0开始算
excelstyles:['text-align']//使用样式,不用填值只写属性,值读取的是html中的
});
}/script
如上既是JS的进阶导出,操作简单,容易上手
但有个弊端就是分页的情况下,只能导出分页出的数据,毕竟这就是导出HTML内TABLE有的东西,数据在数据库或后台的也就无能为力,所以这个适合的是无分页的TABLE导出
3. 额外说明
tableExport.js是gitHub上的hhurz大牛的一个开源项目,需要下载该JS的可以点击链接进入gitHub下载或在我的百度网盘下载 密码:oafu
tableExport.js不仅仅是个导出Excel的JS,他还可以导出CSV、DOC、JSON、PDF、PNG、SQL、TSV、TXT、XLS (Excel 2000 HTML format)、XLSX (Excel 2007 Office Open XML format)、XML (Excel 2003 XML Spreadsheet format)、XML (Raw xml)多种格式,具体使用可以参考hhurz的使用介绍
本人在之前找了好几个导出Excel的都有各种各样的问题(乱码,无响应,无样式),这个是目前找到最好的一个了,能解决乱码问题,能有样式,非常强大
怎么用java实现导出excel
/**
* @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;
}
}
}