Java 批量下载excel,并对excel赋值,压缩为zip文件(POI版)
package com.neusoft.nda.servlet;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
import com.neusoft.nda.electronicrecord.service.MediaFileServlet;
import com.neusoft.nda.objectutils.utils.ObjectUtil;
import com.neusoft.nda.om.constants.ActionTypeConst;
import com.neusoft.nda.om.manager.IContainer;
import com.neusoft.nda.om.manager.IObjectManager;
import com.neusoft.nda.om.manager.ObjectManagerFactory;
import com.neusoft.nda.om.manager.dto.OMContextDTO;
import com.neusoft.nda.persistence.dataoperator.dto.ObjectDTO;
import com.neusoft.nda.utils.utils.ToolsUtil;
public class BeiKaoServlet extends HttpServlet{
/**
*
*/
private static final long serialVersionUID = -1166903384923406516L;
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
downloadMulti(req, resp);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}
private void writeExcel(String finalXlsxPath,String id,String tempPath){
//注释掉了我的业务逻辑,下面只是对单元格的操作
//单元格如果没创建,则代码里创建createCell,如果已经创建,代码里改成getCell
File finalXlsxFile = createNewFile(finalXlsxPath);//复制模板,
Workbook workBook = null;
try {
workBook = getWorkbok(finalXlsxFile);
} catch (IOException e1) {
e1.printStackTrace();
}
Sheet sheet = workBook.getSheetAt(0);
workBook.createCellStyle().setAlignment(HSSFCellStyle.ALIGN_CENTER);//水平居中
workBook.createCellStyle().setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//垂直居中
//sheet 第一页
Row row1= sheet.getRow(2);
Cell c1=row1.getCell(6);
c1.setCellValue("");//3行7列
//sheet 第2页
Sheet sheet2 = workBook.getSheetAt(1);
HSSFFont font1 = (HSSFFont) workBook.createFont();
font1.setFontName("宋体");
font1.setFontHeightInPoints((short) 10);//设置字体大小
HSSFCellStyle cellStyle1 = (HSSFCellStyle) workBook.createCellStyle(); //卷内样式
cellStyle1.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 居中
cellStyle1.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//垂直居中
cellStyle1.setFont(font1);//宋体10号
cellStyle1.setWrapText(true);
cellStyle1.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下边框
cellStyle1.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框
cellStyle1.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框
cellStyle1.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框
//从4行开始
Row rowsheet4= sheet2.createRow(k+3);
rowsheet4.setHeight((short) (42*20));//行高
Cell csheet=rowsheet4.createCell(0);//序号
csheet.setCellValue("");
csheet.setCellStyle(cellStyle1);
//封面 sheet3
Sheet sheet3 = workBook.getSheetAt(2);
//样式
HSSFCellStyle cellStyle=(HSSFCellStyle) workBook.createCellStyle();
cellStyle.setWrapText(true); //自动换行
HSSFFont font = (HSSFFont) workBook.createFont();
font.setFontName("宋体");
font.setFontHeightInPoints((short) 12);//设置字体大小
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//粗体显示
cellStyle.setFont(font);
cellStyle.setIndention((short) 2);//缩进2
cellStyle.setAlignment(CellStyle.ALIGN_LEFT);//靠左
Row rowsheet62= sheet3.getRow(5);
Cell csheet62=rowsheet62.getCell(1);
csheet62.setCellValue("");//
csheet62.setCellStyle(cellStyle);//自动换行
FileOutputStream out = null;
try {
out = new FileOutputStream(tempPath + File.separator + oto1.getBean().getString("DH")+".xls");
} catch (FileNotFoundException e2) {
e2.printStackTrace();
}
try {
workBook.write(out);
} catch (IOException e1) {
e1.printStackTrace();
}
try {
if (out != null) {
out.flush();
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 判断excel格式版本
*
* @param file
* @return
* @throws IOException
*/
private Workbook getWorkbok(File file) throws IOException {
Workbook wb = null;
FileInputStream in = new FileInputStream(file);
if (file.getName().endsWith(".xls")) { // Excel 2003
wb = new HSSFWorkbook(in);
} else if (file.getName().endsWith("xlsx")) { // Excel 2007/2010
wb = new XSSFWorkbook(in);
}
return wb;
}
private File createNewFile(String path) {
// 读取模板,并赋值到新文件************************************************************
// 文件模板路径
File file = new File(path);
if (!file.exists()) {
System.out.println("原模板文件不存在");
}
// 保存文件的路径
String realPath = file.getParent();
// 新的文件名
String newFileName =System.currentTimeMillis()+ ".xls";
// 判断路径是否存在
File dir = new File(realPath);
if (!dir.exists()) {
dir.mkdirs();
}
// 写入到新的excel
File newFile = new File(realPath, newFileName);
try {
newFile.createNewFile();
// 复制模板到新文件
FileUtils.copyFile(file, newFile);
} catch (Exception e) {
e.printStackTrace();
}
return newFile;
}
/**
*
* <p>下载多个文件</p>
*
* @comment [注释说明]
* @author yu-b, 2013-1-9
* @since NDAS 2.0
*
* @param request
* @param response
* @throws IOException
*/
private void downloadMulti(HttpServletRequest request,
HttpServletResponse response) throws IOException
{
String sourcePath = getServletContext().getRealPath("/WEB-INF/")
+ "/conf/ExcelModel/beikao.xls"; // 读取Excel文档 //用自己本地的路径
String id = request.getParameter("id");
String[] idsArr = id.split("_");
List<String> ids = Arrays.asList(idsArr);
// 下载文件名
String downFileName = "download.zip";
// 生成缓存文件夹名
String sesstionId = request.getSession().getId();
String tempPath = ToolsUtil.getRealPath("platform" + File.separator
+ "seasplatform" + File.separator
+ sesstionId + File.separator + Calendar.getInstance().getTimeInMillis());
File tempFile = new File(tempPath);
if (!tempFile.exists())
{
tempFile.mkdirs();
}
OutputStream respOut = response.getOutputStream();
response.setCharacterEncoding("utf-8");
response.setHeader("Content-Disposition", "attachment; filename=\""
+ new String(downFileName.getBytes(), "ISO-8859-1") + "\"");// 解决中文乱码问题
// 设置响应头和下载保存的文件名
String mimeType = null;
mimeType = this.getServletContext().getMimeType("zip");
if (StringUtils.isEmpty(mimeType))
{
mimeType = "APPLICATION/OCTET-STREAM";
}
response.setContentType(mimeType);
for(String objectId : ids)
{
writeExcel(sourcePath, objectId, tempPath);
}
creasteZip(new File(tempPath), respOut);
try
{
deleteFile(new File(tempPath));
respOut.flush();
respOut.close();
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
/**
* 递归删除文件夹
*
* @param file
* @return void
*/
private void deleteFile(File file)
{
if (file.exists())
{// 判断文件是否存在
if (file.isFile())
{// 判断是否是文件
file.delete();// 删除文件
}
else if (file.isDirectory())
{// 否则如果它是一个目录
File[] files = file.listFiles();// 声明目录下所有的文件 files[];
for (int i = 0; i < files.length; i++)
{// 遍历目录下所有的文件
deleteFile(files[i]);// 把每个文件用这个方法进行迭代
}
file.delete();// 删除文件夹
}
}
else
{
System.out.println("所删除的文件不存在");
}
}
/**
* 压缩文件或者文件目录到指定的zip或者rar包
*
* @param inputFile 参数为文件类型的要压缩的文件或者文件夹
* @param out 输出流
* @return void
*/
private synchronized void creasteZip(File inputFile, OutputStream resOut)
{
ZipOutputStream out = null;
try
{
out = new ZipOutputStream(resOut);
out.setEncoding("gbk");
zip(inputFile, out, "");
}
catch (IOException e)
{
}
finally
{
try
{
out.close();
}
catch (IOException ex)
{
Logger.getLogger(MediaFileServlet.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
/**
* 压缩文件或者文件目录到指定的zip或者rar包
*
* @param inputFile 参数为文件类型的要压缩的文件或者文件夹
* @param out 输出流
* @param base 基文件夹
* @return void
*/
private synchronized void zip(File inputFile, ZipOutputStream out, String base) throws IOException
{
if (inputFile.isDirectory())
{
File[] inputFiles = inputFile.listFiles();
out.putNextEntry(new ZipEntry(base + "/"));
base = base.length() == 0 ? "" : base + "/";
for (int i = 0; i < inputFiles.length; i++)
{
zip(inputFiles[i], out, base + inputFiles[i].getName());
}
}
else
{
if (base.length() > 0)
{
out.putNextEntry(new ZipEntry(base));
}
else
{
out.putNextEntry(new ZipEntry(inputFile.getName()));
}
FileInputStream in = new FileInputStream(inputFile);
try
{
int c;
byte[] by = new byte[1024];
while ((c = in.read(by)) != -1)
{
out.write(by, 0, c);
}
}
catch (IOException e)
{
}
finally
{
in.close();
}
}
}
}
Java 批量下载excel,并对excel赋值,压缩为zip文件(POI版)的更多相关文章
- java+批量下载文件到指定文件夹
需求 导出文件后存留在了服务器中,需要提供下载按钮,点击后可下载到本地:(因为涉及多个文件,下载前先将文件进行压缩,提供下载压缩文件) 效果预览 代码 主要方法 /** * 下载生成的所有在线 ...
- java批量下载,将多文件打包成zip格式下载
现在的需求的: 根据产品族.产品类型,下载该产品族.产品类型下面的pic包: pic包是zip压缩文件: t_product表: 这些包以blob形式存在另一张表中: t_imagefile表: 现在 ...
- Java批量下载文件并zip打包
客户需求:列表勾选需要的信息,点击批量下载文件的功能.这里分享下我们系统的解决方案:先生成要下载的文件,然后将其进行压缩,生成zip压缩文件,然后使用浏览器的下载功能即可完成批量下载的需求.以下是zi ...
- java批量下载
最近做了一些有关批量压缩下载的功能,网上也找了一些资源,但都不是太全面,所以自己整理一份,已备不时之需. 直接上代码: // 获取项目路径 private static String WEBC ...
- java批量下载文件为zip包
批量下载文件为zip包的工具类 package com.meeno.trainsys.util; import javax.servlet.http.HttpServletRequest; impor ...
- java+批量下载大文件
我们平时经常做的是上传文件,上传文件夹与上传文件类似,但也有一些不同之处,这次做了上传文件夹就记录下以备后用. 这次项目的需求: 支持大文件的上传和续传,要求续传支持所有浏览器,包括ie6,ie7,i ...
- Java—将文件压缩为zip文件
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import ...
- JAVA 批量下载服务器文件到本地指定文件夹并重命名
/** * @功能 下载文件到指定文件夹并重命名 * @param url 请求的路径 * @param filePath 文件将要保存的目录 * @param filename 保存到本地的文件名 ...
- Java—将文件夹压缩为zip文件
import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java ...
随机推荐
- jQuery on()方法使用
jQuery on()方法 基本语法: 语法结构一: $(selector).on(event,function) 语法结构二: $(selector).on(events,[selector],[d ...
- 【转】最近很火的 Safe Area 到底是什么
iOS 7 之后苹果给 UIViewController 引入了 topLayoutGuide 和 bottomLayoutGuide 两个属性来描述不希望被透明的状态栏或者导航栏遮挡的最高位置(st ...
- datagrip离线安装驱动jar
问题描述: datagrip离线安装驱动,在线的安装驱动一般默认安装在当前用户下.DataGrip xxxx 问题解决: 在线在线下载驱动jar,复制jar到内网离线环境 01.外网已经存在的jar提 ...
- 【Linux】Centos下安装ffmpeg
一.准备工作 1.系统环境:CentOS release 6.9 (Final) 2.安装依赖包 yum install -y autoconf automake cmake freetype-dev ...
- [STF手机设备管理平台]连接其它操作系统上的安卓设备实操介绍
一.背景 看到之前曾有人发贴,贴名[stf 连接各操作系统上安卓设备的操作方法分享],介绍了一下,虽然说方法和理论都有,但下述评论中还是有很多人不知如何操作,特别是不知道stf provider命令如 ...
- (原)visual studio 2015中添加dll路径
转载请注明出处: https://www.cnblogs.com/darkknightzh/p/9922033.html 使用vs2015调用opencv 3.4时,除了需要在“VC++目录”中”包含 ...
- 使用phpstorm进行PHP断点调试
PHP开发中都说一个会偷懒的程序员才是合格的程序员,在PHP开发中调试是必须要有的,可能要重复很多次的去调试,一次又一次,今天我们就来教教大家如何偷懒的,那么就来讲讲使用phpstorm进行偷懒吧! ...
- Android Studio系列-签名打包
本篇博客纪录使用Android Studio对项目进行签名打包,跟Eclipse大同小异,读者朋友注意其中到差别. 第一步 创建签名文件 第二步 填写签名参数 第三步 选择构建类型 第四步 查看生成第 ...
- CNN(卷积神经网络)、RNN(循环神经网络)、DNN,LSTM
http://cs231n.github.io/neural-networks-1 https://arxiv.org/pdf/1603.07285.pdf https://adeshpande3.g ...
- C语言 · 滑动解锁
题目:滑动解锁 滑动解锁是智能手机一项常用的功能.你需要在3x3的点阵上,从任意一个点开始,反复移动到一个尚未经过的"相邻"的点.这些划过的点所组成的有向折线,如果与预设的折线在图 ...