最近项目遇到一个需求,需要一次性导出全部数据,而且是按照500条数据一个文件。
话不多说,开始。
新增excel工具类
可以直接复制
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.hssfcolor;
import org.apache.poi.ss.util.cellrangeaddress;
//关于下面这两个包,可以直接用java自带的,也可以导入
//我这里是导入的,可以进行一个编码的设置,不过我是没有设置成功,反而乱码
//建议里面的文件名什么的都用英文,不用担心乱码,哈哈
import org.apache.tools.zip.zipentry;
import org.apache.tools.zip.zipoutputstream;
import java.io.*;
import java.util.arraylist;
import java.util.list;
public class exportexcel {
// 显示的导出表的标题
private string title;
// 导出表的列名
private string[] rowname;
private list<object[]> datalist = new arraylist<object[]>();
public exportexcel() {
}
// 构造函数,传入要导出的数据
public exportexcel(string title, string[] rowname, list<object[]> datalist) {
this.datalist = datalist;
this.rowname = rowname;
this.title = title;
}
// 导出数据
public void export(outputstream out) throws exception {
try {
hssfworkbook workbook = new hssfworkbook();
hssfsheet sheet = workbook.createsheet(title);
// 产生表格标题行
hssfrow rowm = sheet.createrow(0);
hssfcell celltitle = rowm.createcell(0);
//sheet样式定义【】
hssfcellstyle columntopstyle = this.getcolumntopstyle(workbook);
hssfcellstyle style = this.getstyle(workbook);
sheet.addmergedregion(new cellrangeaddress(0, 1, 0, (rowname.length - 1)));
celltitle.setcellstyle(columntopstyle);
celltitle.setcellvalue(title);
// 定义所需列数
int columnnum = rowname.length;
hssfrow rowrowname = sheet.createrow(2);
// 将列头设置到sheet的单元格中
for (int n = 0; n < columnnum; n++) {
hssfcell cellrowname = rowrowname.createcell(n);
cellrowname.setcelltype(hssfcell.cell_type_string);
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 {
workbook.write(out);
} catch (exception e) {
e.printstacktrace();
}
}
} catch (exception e) {
}
}
/**
* 列头单元格样式
*/
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.setborderright(hssfcellstyle.border_thin);
// 设置顶边框
style.settopbordercolor(hssfcolor.black.index);
// 设置顶边框颜色
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 void zipfiles(file[] srcfile, file zipfile) {
zipoutputstream out = null;
byte[] buf = new byte[1024];
try {
out = new zipoutputstream(new fileoutputstream(
zipfile));
// out.setencoding("utf-8");
for (int i = 0; i < srcfile.length; i++) {
fileinputstream in = new fileinputstream(srcfile[i]);
out.putnextentry(new zipentry(srcfile[i].getname()));
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.closeentry();
in.close();
}
out.close();
} catch (ioexception e) {
e.printstacktrace();
}
}
/***
* 删除指定文件夹下所有文件
*
* @param path 文件夹完整绝对路径
* @return
*/
public static boolean delallfile(string path) {
boolean flag = false;
file file = new file(path);
if (!file.exists()) {
return flag;
}
if (!file.isdirectory()) {
return flag;
}
string[] templist = file.list();
file temp = null;
for (int i = 0; i < templist.length; i++) {
if (path.endswith(file.separator)) {
temp = new file(path + templist[i]);
} else {
temp = new file(path + file.separator + templist[i]);
}
if (temp.isfile()) {
temp.delete();
}
if (temp.isdirectory()) {
delallfile(path + "/" + templist[i]);// 先删除文件夹里面的文件
flag = true;
}
}
return flag;
}
}
具体业务代码
注:
1、对数据预处理
string title = "业主信息表";//这个是表格的标题,不是文件名
//每个单元格的标题,具体内容自己设置
string[] rowsname = {"业主id", "姓名","身份证号","楼栋号", "单元号", "楼层号", "房间号", "电话号码"};
//存放需要的数据
arraylist<object[]> datalist = new arraylist<>();
object[] objs = null;
//根据业务需求,查询出要导出的数据
list<citroommaster> list = citroommasterservice.getlist();
//将全部数据按需加载到datalist中
//对null值进行一个处理,因为如果是空的导入文件中会造成整个文件损坏,读取不到任何数据
for (citroommaster c :list) {
objs = new object[rowsname.length];
objs[0] = c.getid();
objs[1] = c.getusername() == null?"未录入":c.getusername();
objs[2] = c.getidcard() == null?"未录入":c.getidcard();
objs[3] = c.getbuilding() == null?"未录入":c.getbuilding();
objs[4] = c.getunit() == null?"未录入":c.getunit();
objs[5] = c.getroomlevel() == null?"未录入":c.getroomlevel();
objs[6] = c.getroomnum() == null?"未录入":c.getroomnum();
objs[7] = c.gettel() == null?"未录入":c.gettel();
datalist.add(objs);
}
2、按500条数据进行excel文件生成
// 将excel导出的文件位置,临时文件,注意,一定是一个不存在的文件,因为后面会把这个文件夹删完
string filepath = "c:\\小区业主信息"+ file.separator;
// 得到此路径下文件
file filedir = new file(filepath);
//创建文件夹
if (!filedir.exists() && !filedir.isdirectory()) {
filedir.mkdirs();
}
// 用于存放生成的excel文件名称
list<string> filenames = new arraylist<string>();
// 导出excel文件的路径
string fullfilepath = "";
//输出流
fileoutputstream os = null;
//拿到整个需要循环导出的次数
int length = list.size()%500 == 0 ? list.size()/500 : (list.size()/500)+1;
for (int i = 0; i < length; i++) {
//给文件命名。随机命名 自定义
string filename = "ownerinformation-" + string.valueof(system.currenttimemillis()).substring(4, 13) + ".xls";
//生成excel文件导出的路径
fullfilepath = filepath + file.separator + filename;
filenames.add(fullfilepath);
os = new fileoutputstream(fullfilepath);
//调用poi的工具类
int end = 0;
//对list进行截取,每500条数据
exportexcel ex = new exportexcel(title, rowsname, datalist.sublist(i*500,end = (i+1)*500<=list.size()?(i+1)*500:list.size()));
try {
ex.export(os);
} catch (exception e) {
e.printstacktrace();
}
os.flush();
os.close();
os = null;
}
3、将存放excel的文件夹压缩导出
就完成需求了
//告诉浏览器数据格式,将头和数据传到前台
string headstr = "attachment; filename=\"" + zip.getname() + "\"";
response.setcontenttype("application/zip");
// response.setheader("location",zip.getname());
response.setheader("content-disposition", headstr);
outputstream out = response.getoutputstream();
inputstream in = new fileinputstream(zipfilepath);
byte[] buffer = new byte[1024];
int i = -1;
while ((i = in.read(buffer)) != -1) {
out.write(buffer, 0, i);
}
out.flush();
out.close();
in.close();
out = null;
try {
excelutil.delallfile(filepath); // 删除完里面所有内容
filepath = filepath.tostring();
java.io.file myfilepath = new java.io.file(filepath);
myfilepath.delete(); // 删除空文件夹
} catch (exception e) {
e.printstacktrace();
}
最后再说一点:
- 还是关于中文乱码的问题,本来最开始的我是用的中文写文件名,并且在自己电脑上测试的时候是么有乱码的。
- 但是部署到公司服务器上,就乱码了,怀疑是编码不一致问题导致的,因为时间问题,也没有去调试了。
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论