提交POI导出Excel导出功能

This commit is contained in:
zhangqinbin
2021-01-06 19:09:57 +08:00
parent fc1b5a00b1
commit 974317cd43
2 changed files with 51 additions and 7 deletions

View File

@ -8,9 +8,8 @@ import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.xssf.usermodel.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@ -247,4 +246,35 @@ public class ExportConstant {
sheet.setColumnWidth(i,colList.get(i));//列宽
}
}
public static void exportFile(HttpServletResponse response,File file){
OutputStream out = null;
InputStream is = null;
try {
response.addHeader("content-disposition", "attachment;filename="
+ java.net.URLEncoder.encode(file.getName(), "utf-8"));
out = response.getOutputStream();
is = new FileInputStream(file);
byte[] b = new byte[4096];
int size = is.read(b);
while (size > 0) {
out.write(b, 0, size);
size = is.read(b);
}
out.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(is!=null)is.close();
if(out!=null)out.close();
} catch (IOException e) {
e.printStackTrace();
}
file.delete();
}
}
}

View File

@ -11,6 +11,7 @@ import java.util.List;
public class ExportText {
public static void main(String[] arge){
ExcelTable table = new ExcelTable("测试1");
table.setFileName("测试11");
List<ExcelTd> list = new ArrayList<>();
list.add(new ExcelTd().setTdValue("1111"));
list.add(new ExcelTd().setTdValue("1222"));
@ -20,17 +21,19 @@ public class ExportText {
table.add(new ExcelTr().setExcelTdList(list));
OutputStream os = null;
File file = null;
InputStream inputStream = null;
try {
String path = "D:/恒熠/联通/需求/3.0/评审/common测试.xlsx";
File file = ExportConstant.generateExcelByTable(table);
InputStream inputStream = new FileInputStream(file);
String path = "D:/恒熠/联通/需求/3.0/评审/";
file = ExportConstant.generateExcelByTable(table);
inputStream = new FileInputStream(file);
// 1K的数据缓冲
byte[] bs = new byte[1024];
// 读取到的数据长度
int len;
// 输出的文件流保存到本地文件
File tempFile = new File(path);
File tempFile = new File(path+file.getName());
os = new FileOutputStream(tempFile);
// 开始读取
while ((len = inputStream.read(bs)) != -1) {
@ -38,6 +41,17 @@ public class ExportText {
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(inputStream!=null)inputStream.close();
if(os!=null)os.close();
} catch (IOException e) {
e.printStackTrace();
}
if(file!=null){
file.delete();
}
}
}
}