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版)的更多相关文章

  1. java+批量下载文件到指定文件夹

    需求 导出文件后存留在了服务器中,需要提供下载按钮,点击后可下载到本地:(因为涉及多个文件,下载前先将文件进行压缩,提供下载压缩文件) 效果预览 代码 主要方法 /**     * 下载生成的所有在线 ...

  2. java批量下载,将多文件打包成zip格式下载

    现在的需求的: 根据产品族.产品类型,下载该产品族.产品类型下面的pic包: pic包是zip压缩文件: t_product表: 这些包以blob形式存在另一张表中: t_imagefile表: 现在 ...

  3. Java批量下载文件并zip打包

    客户需求:列表勾选需要的信息,点击批量下载文件的功能.这里分享下我们系统的解决方案:先生成要下载的文件,然后将其进行压缩,生成zip压缩文件,然后使用浏览器的下载功能即可完成批量下载的需求.以下是zi ...

  4. java批量下载

    最近做了一些有关批量压缩下载的功能,网上也找了一些资源,但都不是太全面,所以自己整理一份,已备不时之需. 直接上代码: // 获取项目路径     private static String WEBC ...

  5. java批量下载文件为zip包

    批量下载文件为zip包的工具类 package com.meeno.trainsys.util; import javax.servlet.http.HttpServletRequest; impor ...

  6. java+批量下载大文件

    我们平时经常做的是上传文件,上传文件夹与上传文件类似,但也有一些不同之处,这次做了上传文件夹就记录下以备后用. 这次项目的需求: 支持大文件的上传和续传,要求续传支持所有浏览器,包括ie6,ie7,i ...

  7. Java—将文件压缩为zip文件

    import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import ...

  8. JAVA 批量下载服务器文件到本地指定文件夹并重命名

    /** * @功能 下载文件到指定文件夹并重命名 * @param url 请求的路径 * @param filePath 文件将要保存的目录 * @param filename 保存到本地的文件名 ...

  9. Java—将文件夹压缩为zip文件

    import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java ...

随机推荐

  1. $.contents().find设置的data在iframe子页面无法获取值

    <iframe src="iframe16.html" id="iframe16" name="iframe16"></i ...

  2. gitbook安装与使用,并使用docker部署

    本文简单介绍如何安装并使用gitbook,最后如何使用docker构建书籍镜像. 1. 前置条件 需要Nodejs环境,安装npm,国内用户再安装cnpm npm install -g cnpm -- ...

  3. fiddle扩展

    扩展地址:http://www.telerik.com/fiddler/add-ons 证书选择 ios设置证书生成 (CertMaker for iOS and Android) 证书查看 (Fid ...

  4. OpenWrt 对外网开放vsftp服务和samba服务

    对WAN开放vsFTP OpenWrt默认启动了vsftp服务, 在Luci上没找到配置界面, 但是后台是有这个服务的, 如果在Openwrt的lan下, 可以直接使用FileZilla之类的客户端连 ...

  5. 解决Visual Studio调试突然变慢卡死的问题

    最开始摸不到头脑,之前还能好好调试的啊.后来在VS的调试菜单的符号选项里面发现了系统环境变量_NT_SYMBOL_PATH 的值为:srv*c:\symbols*http://msdl.microso ...

  6. C#反射实现 C# 反射 判断类的延伸类型 使用代码生成工具Database2Sharp快速生成工作流模块控制器和视图代码 C# ADO.NET的SqlDataReader对象,判断是否包含指定字段 页面中添加锚点的几种方式 .net 简单实用Log4net(多个日志配置文件) C# 常用小点

    C#反射实现   一.反射概念: 1.概念: 反射,通俗的讲就是我们在只知道一个对象的内部而不了解内部结构的情况下,通过反射这个技术可以使我们明确这个对象的内部实现. 在.NET中,反射是重要的机制, ...

  7. Atitit 分布式管理 vs 集中式管理

    Atitit 分布式管理 vs 集中式管理 1. 集中式管理缺点 1 1.1. 单点故障 1 1.2. 没有灵活性 1 1.3. 打败vs 征服 参考 尼可罗·马基雅弗利编著的<君主论> ...

  8. jQuery创建元素和添加子元素

    var li = $("<li class=\"TopNav arrow\" secondMenu=\"menu_" + i + "\ ...

  9. 强化学习-MDP(马尔可夫决策过程)算法原理

    1. 前言 前面的强化学习基础知识介绍了强化学习中的一些基本元素和整体概念.今天讲解强化学习里面最最基础的MDP(马尔可夫决策过程). 2. MDP定义 MDP是当前强化学习理论推导的基石,通过这套框 ...

  10. CPU与GPU性能的比较报告

    运行时间分析 不同的模型在cpu和gpu下的时间差异较大,一般来说gpu会比cpu快5-20倍.我们选用了最常用的inception v3的分类模型,输入图片尺寸为:3x299x299. GPU 在一 ...