乔山办公网我们一直在努力
您的位置:乔山办公网 > excel表格制作 > java导出数据到<em>excel</em>的几种方法的比较

java导出数据到<em>excel</em>的几种方法的比较

作者:乔山办公网日期:

返回目录:excel表格制作


用java写完文件后需要关闭文件流,如果不关闭就会报这个错。
因为你的文件内容写完了,所以内容没有缺失,但excel检测到文件没有正常结束,所以报错。
另存是由excel重写了完整的文件,所以可以解决问题。
关闭文件例子:
FileOutputStream os = new FileOutputStream("workbook.xls");
wb.write(os);
os.close();

Excel的两种导出入门方法(JAVA与JS)

最近在做一个小项目作为练手,其中使用到了导出到Excel表格,一开始做的是使用JAVA的POI导出的,但因为我的数据是爬虫爬出来的,数据暂时并不保存在数据库或后台,所以直接显示在HTML的table,需要下载时又要将数据传回后台然后生成Excel文件,最后再从服务器下载到本地,过程几度经过网络传输,感觉比较耗时与浪费性能,于是想着在HTML中的Table直接导到Excel中节约资源

JAVA导出EXCEL(.xls)

导出Excel用的插件是apache的poi.jar,maven地址如下

<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version></dependency>

1. 简单应用

先来个简化无样式的Excel导出,由于我的数据存在JSON中,所以形参是JSONArray,朋友们根据自己的实际数据类型(Map,List,Set等)传入即可 ,代码如下

/**
* 创建excel并填入数据
* @e79fa5e98193e58685e5aeb9336author 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"></script><script type="text/javascript">
function exportExcelWithJS(){    //获取要导出Excel的表格对象并设置tableExport方法,设置导出类型type为excel
$('#tableId').tableExport({      type:'excel'
});
}</script><button 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的都有各种各样的问题(乱码,无响应,无样式),这个是目前找到最好的一个了,能解决乱码问题,能有样式,非常强大


在保护状态下execl的格式有可能正在被使用,你这边修改,准确说是线程冲突,一般excel值会作为导出文件的模板,是不会编辑的。你可以在读的时候判断execl是否正在被使用。
下面的代码问题,你可以参考
package com.hwt.glmf.common;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
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.hssf.util.CellRangeAddress;
import org.apache.poi.hssf.util.HSSFColor;

/**
* 导出Excel公共方法
* @version 1.0
*
* @author wangcp
*
*/
public class ExportExcel extends BaseAction {

//显示的导出表的标题
private String title;
//导出表的列名
private String[] rowName ;

private List<Object[]> dataList = new ArrayList<Object[]>();

HttpServletResponse response;

//构造方法,传入要导出的数据
public ExportExcel(String title,String[] rowName,List<Object[]> dataList){
this.dataList = dataList;
this.rowName = rowName;
this.title = title;
}

/*
* 导出数据
* */
public void export() throws Exception{
try{
HSSFWorkbook workbook = new HSSFWorkbook(); // 创建工作簿对象
HSSFSheet sheet = workbook.createSheet(title); // 创建工作表

// 产生表格标题行
HSSFRow rowm = sheet.createRow(0);
HSSFCell cellTiltle = rowm.createCell(0);

//sheet样式定义【getColumnTopStyle()/getStyle()均为自定义方法 - 在下面 - 可扩展】
HSSFCellStyle columnTopStyle = this.getColumnTopStyle(workbook);//获取列头样式对象
HSSFCellStyle style = this.getStyle(workbook); //单元格样式对象

sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, (rowName.length-1)));
cellTiltle.setCellStyle(columnTopStyle);
cellTiltle.setCellValue(title);

// 定义所需列数
int columnNum = rowName.length;
HSSFRow rowRowName = sheet.createRow(2); // 在索引2的位置创建行(最顶端的行开始的第二行)

// 将列头设置到sheet的单元格中
for(int n=0;n<columnNum;n++){
HSSFCell cellRowName = rowRowName.createCell(n); //创建列头对应个数的单元格
cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING); //设置列头单元格的7a686964616fe78988e69d83330数据类型
HSSFRichTextString text = new HSSFRichTextString(rowName[n]);
cellRowName.setCellValue(text); //设置列头单元格的值
cellRowName.setCellStyle(columnTopStyle); //设置列头单元格样式
}

//将查询出的数据设置到sheet对应的单元格中
for(int i=0;i<dataList.size();i++){

Object[] obj = dataList.get(i);//遍历每个对象
HSSFRow row = sheet.createRow(i+3);//创建所需的行数

for(int j=0; j<obj.length; j++){
HSSFCell cell = null; //设置单元格的数据类型
if(j == 0){
cell = row.createCell(j,HSSFCell.CELL_TYPE_NUMERIC);
cell.setCellValue(i+1);
}else{
cell = row.createCell(j,HSSFCell.CELL_TYPE_STRING);
if(!"".equals(obj[j]) && obj[j] != null){
cell.setCellValue(obj[j].toString()); //设置单元格的值
}
}
cell.setCellStyle(style); //设置单元格样式
}
}
//让列宽随着导出的列长自动适应
for (int colNum = 0; colNum < columnNum; colNum++) {
int columnWidth = sheet.getColumnWidth(colNum) / 256;
for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) {
HSSFRow currentRow;
//当前行未被使用过
if (sheet.getRow(rowNum) == null) {
currentRow = sheet.createRow(rowNum);
} else {
currentRow = sheet.getRow(rowNum);
}
if (currentRow.getCell(colNum) != null) {
HSSFCell currentCell = currentRow.getCell(colNum);
if (currentCell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
int length = currentCell.getStringCellValue().getBytes().length;
if (columnWidth < length) {
columnWidth = length;
}
}
}
}
if(colNum == 0){
sheet.setColumnWidth(colNum, (columnWidth-2) * 256);
}else{
sheet.setColumnWidth(colNum, (columnWidth+4) * 256);
}
}

if(workbook !=null){
try
{
String fileName = "Excel-" + String.valueOf(System.currentTimeMillis()).substring(4, 13) + ".xls";
String headStr = "attachment; filename=\"" + fileName + "\"";
response = getResponse();
response.setContentType("APPLICATION/OCTET-STREAM");
response.setHeader("Content-Disposition", headStr);
OutputStream out = response.getOutputStream();
workbook.write(out);
}
catch (IOException e)
{
e.printStackTrace();
}
}

}catch(Exception e){
e.printStackTrace();
}

}

/*
* 列头单元格样式
*/
public HSSFCellStyle getColumnTopStyle(HSSFWorkbook workbook) {

// 设置字体
HSSFFont font = workbook.createFont();
//设置字体大小
font.setFontHeightInPoints((short)11);
//字体加粗
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
//设置字体名字
font.setFontName("Courier New");
//设置样式;
HSSFCellStyle style = workbook.createCellStyle();
//设置底边框;
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
//设置底边框颜色;
style.setBottomBorderColor(HSSFColor.BLACK.index);
//设置左边框;
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
//设置左边框颜色;
style.setLeftBorderColor(HSSFColor.BLACK.index);
//设置右边框;
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
//设置右边框颜色;
style.setRightBorderColor(HSSFColor.BLACK.index);
//设置顶边框;
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
//设置顶边框颜色;
style.setTopBorderColor(HSSFColor.BLACK.index);
//在样式用应用设置的字体;
style.setFont(font);
//设置自动换行;
style.setWrapText(false);
//设置水平对齐的样式为居中对齐;
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
//设置垂直对齐的样式为居中对齐;
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

return style;

}

/*
* 列数据信息单元格样式
*/
public HSSFCellStyle getStyle(HSSFWorkbook workbook) {
// 设置字体
HSSFFont font = workbook.createFont();
//设置字体大小
//font.setFontHeightInPoints((short)10);
//字体加粗
//font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
//设置字体名字
font.setFontName("Courier New");
//设置样式;
HSSFCellStyle style = workbook.createCellStyle();
//设置底边框;
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
//设置底边框颜色;
style.setBottomBorderColor(HSSFColor.BLACK.index);
//设置左边框;
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
//设置左边框颜色;
style.setLeftBorderColor(HSSFColor.BLACK.index);
//设置右边框;
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
//设置右边框颜色;
style.setRightBorderColor(HSSFColor.BLACK.index);
//设置顶边框;
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
//设置顶边框颜色;
style.setTopBorderColor(HSSFColor.BLACK.index);
//在样式用应用设置的字体;
style.setFont(font);
//设置自动换行;
style.setWrapText(false);
//设置水平对齐的样式为居中对齐;
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
//设置垂直对齐的样式为居中对齐;
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

return style;

}
}

参考代码 :

public static void createColHeader(HSSFSheet sheet, CellStyle cellStyle,String[] columHeader) {if (sheet != null) { sheet.setDefaultColumnWidth(20); HSSFRow row = sheet.createRow(0); for (int i = 0; i < columHeader.length; i++) { HSSFCell cell = row.createCell(i); cell.setCellValue(columHeader[i]); if (cellStyle != null) { cell.setCellStyle(cellStyle); } } freezePane(sheet,0,1,0,1); }}

相关阅读

关键词不能为空
极力推荐

ppt怎么做_excel表格制作_office365_word文档_365办公网