Java用POI往execl表格中写数据,并下载下来有两种方式

1、用poil的API创建表格,并设计好表格格式,然后往里面写数据

 /**
* execl导出 创建表格式,并写入数据
* @param sheetNmae sheet名
* @param tiltle 表头
* @param values 内容
* @param workbook
* @return
*/
public static HSSFWorkbook getHSSFWorkbook(String sheetNmae,
String []tiltle,String[][] values,HSSFWorkbook workbook){ //创建一个Hssfworkbook 对应一个execl文件
if(workbook==null){
workbook=new HSSFWorkbook();
}
//在workbook中添加一个sheet,对应execl文件中的sheet
HSSFSheet sheet=workbook.createSheet(sheetNmae);
sheet.setDefaultColumnWidth((short)13);
//在sheet中添加表头第0行
HSSFRow row=sheet.createRow(0);
//创建单元格,设置表头
HSSFCellStyle style=(HSSFCellStyle)workbook.createCellStyle();
style.setBorderTop(BorderStyle.THIN);
style.setBorderBottom(BorderStyle.THIN);
style.setBorderLeft(BorderStyle.THIN);
style.setBorderRight(BorderStyle.THIN);
//字体样式
HSSFFont font=workbook.createFont();
font.setFontName("微软雅黑");
style.setFont(font); //声明列对象
HSSFCell cell=null; //创建标题
for(int i=0;i<tiltle.length;i++){
cell=row.createCell(i);
cell.setCellValue(tiltle[i]);
cell.setCellStyle(style);
}
//创建内容
//声明列对象
HSSFCell cell2=null;
for(int i=0;i<values.length;i++){
row = sheet.createRow(i + 1);
for(int j=0;j<values[i].length;j++){
//将内容按顺序赋给对应的列对象
cell2=row.createCell(j);
cell2.setCellValue(values[i][j]);
cell2.setCellStyle(style);
}
} return workbook;
}
  /**
*
* @param response
* @param companyCostVo 前端传过来的对象
* @throws Exception
*/
@RequestMapping("/download")
public void download(HttpServletResponse response, CompanyCostVo companyCostVo) throws Exception { Integer year=Integer.valueOf(redisService.valueOperations().get("audityear").toString());
companyCostVo.setYear(year);
//获取数据
List<CompanyCostVo> companyCostVos=companyCostService.selectCompanyCost(companyCostVo);
//exexl标题
String[]title={"序号","公司名称","公交总车辆数","公交收费车辆数","公交收费单价","公交实收金额","公交应收金额",
"农客总车辆数","农客收费车辆数","农客收费单价","农客实收金额","农客应收金额","总实收金额","总应收金额"};
//execl文件名
String fileName=year+"年企业审计费用清算信息表.xls";
//sheetming
String sheetName="费用清算信息";
int len=companyCostVos.size();
String [][] content=new String[len][14];
for(int i=0;i<len;i++){
//content[i]=new String[len];
CompanyCostVo cCostVo=companyCostVos.get(i);
content[i][0]=(i+1)+"";
content[i][1]=cCostVo.getCompanyName();
content[i][2]="无";
if(cCostVo.getVehicleNumGj()!=null){
content[i][2]=cCostVo.getVehicleNumGj().toString();
}
content[i][3]="无";
if(cCostVo.getVehicleNumChargGj()!=null){
content[i][3]=cCostVo.getVehicleNumChargGj().toString();
}
content[i][4]="无";
if(cCostVo.getUnitPriceGj()!=null){
content[i][4]=cCostVo.getUnitPriceGj().toString();
}
content[i][5]="无";
if(cCostVo.getAccountAmountGj()!=null){
content[i][5]=cCostVo.getAccountAmountGj().toString();
}
content[i][6]="无";
if(cCostVo.getAccountPayableGj()!=null){
content[i][6]=cCostVo.getAccountPayableGj().toString();
}
content[i][7]="无";
if(cCostVo.getVehicleNumNk()!=null){
content[i][7]=cCostVo.getVehicleNumNk().toString();
}
content[i][8]="无";
if(cCostVo.getVehicleNumChargNk()!=null){
content[i][8]=cCostVo.getVehicleNumChargNk().toString();
}
content[i][9]="无";
if(cCostVo.getUnitPriceNk()!=null){
content[i][9]=cCostVo.getUnitPriceNk().toString();
}
content[i][10]="无";
if(cCostVo.getAccountAmountNk()!=null){
content[i][10]=cCostVo.getAccountAmountNk().toString();
}
content[i][11]="无";
if(cCostVo.getAccountPayableNk()!=null){
content[i][11]=cCostVo.getAccountPayableNk().toString();
}
content[i][12]="无";
if(cCostVo.getAccountAmount()!=null){
content[i][12]=cCostVo.getAccountAmount().toString();
}
content[i][13]="无";
if(cCostVo.getAccountPayable()!=null){
content[i][13]=cCostVo.getAccountPayable().toString();
} } //创建hssfworkbook
HSSFWorkbook workbook=ExcelUtils.getHSSFWorkbook(sheetName, title, content, null);
//相应到客户端
try{
this.setResponseHeader(response, fileName);
OutputStream osStream=response.getOutputStream();
workbook.write(osStream);
osStream.flush();
osStream.close();
}catch(Exception e){
e.printStackTrace();
}
}
 //发送响应流方法
public void setResponseHeader(HttpServletResponse response, String fileName) {
try {
try {
fileName = new String(fileName.getBytes(),"UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
response.setContentType("application/octet-stream;charset=UTF-8");
response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
response.addHeader("Pargam", "no-cache");
response.addHeader("Cache-Control", "no-cache");
} catch (Exception ex) {
ex.printStackTrace();
}
}

2、自己创建好Execl表的模板,然后直接往里面写入数据

  /**
* 导出异常车辆Ecexl
* @param response
* @param materialGjChangeDetailVo
* @throws Exception
*/
@RequestMapping("/downloadEcexl")
@ResponseBody
public void downloadExecl(HttpServletResponse response, MaterialGjChangeDetailVo materialGjChangeDetailVo) throws Exception{
// 所属公司
SysUser sysUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
if(!"1".equals(sysUser.getType())) {
materialGjChangeDetailVo.setCompanyId(sysUser.getCompanyInfoId());
materialGjChangeDetailVo.setYear(Integer.valueOf(redisService.valueOperations().get("audityear").toString()));
}
//模板地址,项目的根目录
String filePathName = "/templates/新增及更换公交车异常车辆明细表.xls";
InputStream in=this.getClass().getResourceAsStream(filePathName);
POIFSFileSystem poifsFileSystem=new POIFSFileSystem(in);
HSSFWorkbook workbook=new HSSFWorkbook(poifsFileSystem);
HSSFSheet sheet=workbook.getSheet("Sheet1");
sheet.setForceFormulaRecalculation(true);
//设置模板中的一些格式,这里主要是处理某些表格高亮
HSSFCellStyle style=(HSSFCellStyle)workbook.createCellStyle();
style = workbook.createCellStyle();
style.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
style.setFillPattern(FillPatternType.SOLID_FOREGROUND); List<MaterialGjChangeDetailVo> ts = materialGjChangeDetailService.selectMaterialGjChangeDetail(materialGjChangeDetailVo);
String companyName=null;
if(ts!=null&& ts.size()!=0){
companyName=ts.get(0).getCompanyName();
//从第一行第一列开始写入数据,列与行的下标都是从0开始的
sheet.getRow(0).getCell(0).setCellValue("新增及更换公交车明细表("+materialGjChangeDetailVo.getYear()+"年度)");
sheet.getRow(2).getCell(0).setCellValue("被审计单位:"+companyName);
for(int i=0,len1=ts.size();i<len1;i++){
String falg=null;
if(ts.get(i).getFlag()!=null){
falg=ts.get(i).getFlag();
}
for(int j=0,len=falg.length();j<len;j++){
sheet.getRow(5+i).getCell(0).setCellValue(i+1);//第5+i行 第i列 从0开始 0
if(ts.get(i).getPlateNumber()!=null){
sheet.getRow(5+i).getCell(1).setCellValue(ts.get(i).getPlateNumber());//
if(falg!=null&&falg!=null&&falg.charAt(1)=='0'){
sheet.getRow(5+i).getCell(1).setCellStyle(style);
}
}
if(ts.get(i).getPlateColor()!=null){
if (ts.get(i).getPlateColor().equals("100201")) {
sheet.getRow(5+i).getCell(2).setCellValue("黄色");//
} else if (ts.get(i).getPlateColor().equals("100202")) {
sheet.getRow(5+i).getCell(2).setCellValue("蓝色");//
} else if (ts.get(i).getPlateColor().equals("100203")) {
sheet.getRow(5+i).getCell(2).setCellValue("其他");//
} if(falg!=null&&falg.charAt(2)=='0'){
sheet.getRow(5+i).getCell(2).setCellStyle(style);
}
}
if(ts.get(i).getVehicleBrandRegDate()!=null){
sheet.getRow(5+i).getCell(3).setCellValue(ts.get(i).getVehicleBrandRegDate());//
if(falg!=null&&falg.charAt(3)=='0'){
sheet.getRow(5+i).getCell(3).setCellStyle(style);
}
}
if(ts.get(i).getVehicleModel()!=null){
sheet.getRow(5+i).getCell(4).setCellValue(ts.get(i).getVehicleModel());//
if(falg!=null&&falg.charAt(4)=='0'){
sheet.getRow(5+i).getCell(4).setCellStyle(style);
}
}
if(ts.get(i).getManufacturers()!=null){
sheet.getRow(5+i).getCell(5).setCellValue(ts.get(i).getManufacturers());//
if(falg!=null&&falg.charAt(5)=='0'){
sheet.getRow(5+i).getCell(5).setCellStyle(style);
}
}
if(ts.get(i).getBrand()!=null){ sheet.getRow(5+i).getCell(6).setCellValue(ts.get(i).getBrand());//
if(falg!=null&&falg.charAt(6)=='0'){
sheet.getRow(5+i).getCell(6).setCellStyle(style);
}
}
if(ts.get(i).getVehicleLength()!=null){ sheet.getRow(5+i).getCell(7).setCellValue(ts.get(i).getVehicleLength());//
if(falg!=null&&falg.charAt(7)=='0'){
sheet.getRow(5+i).getCell(7).setCellStyle(style);
}
}
if(ts.get(i).getVehicleType()!=null){
if (ts.get(i).getVehicleType().contains("100701")) {
sheet.getRow(5+i).getCell(8).setCellValue("纯电动");//
} else if (ts.get(i).getVehicleType().contains("100702")) {
sheet.getRow(5+i).getCell(8).setCellValue("燃料电池");//
} else if (ts.get(i).getVehicleType().contains("100703")) {
sheet.getRow(5+i).getCell(8).setCellValue("超级电容");//
} else if (ts.get(i).getVehicleType().contains("100704")) {
sheet.getRow(5+i).getCell(8).setCellValue("插电式");//
} else if (ts.get(i).getVehicleType().contains("100705")) {
sheet.getRow(5+i).getCell(8).setCellValue("非插电式");//
} else if (ts.get(i).getVehicleType().contains("100706")) {
sheet.getRow(5+i).getCell(8).setCellValue("其他");//
}
if(falg!=null&&falg.charAt(8)=='0'){
sheet.getRow(5+i).getCell(8).setCellStyle(style);
}
} if(ts.get(i).getExtendInfo()!=null){
if (ts.get(i).getExtendInfo()) {
sheet.getRow(5+i).getCell(9).setCellValue("是");//
} else{
sheet.getRow(5+i).getCell(9).setCellValue("否");//
}
if(falg!=null&&falg.charAt(9)=='0'){
sheet.getRow(5+i).getCell(9).setCellStyle(style);
}
}
if(ts.get(i).getPurchaseInvoiceInfo()!=null){
if (ts.get(i).getPurchaseInvoiceInfo()) {
sheet.getRow(5+i).getCell(10).setCellValue("是");//
} else{
sheet.getRow(5+i).getCell(10).setCellValue("否");//
} if(falg!=null&&falg.charAt(10)=='0'){
sheet.getRow(5+i).getCell(10).setCellStyle(style);
}
}
break;
}
}
}
try{
this.setResponseHeader(response, companyName+"-新增及更换公交车异常车辆明细表.xls");
OutputStream osStream=response.getOutputStream();
workbook.write(osStream);
osStream.flush();
osStream.close();
}catch(Exception e){
e.printStackTrace();
}
}
 /**
*
* @param response
* @param fileName 文件名
*/
public void setResponseHeader(HttpServletResponse response, String fileName) {
try {
try {
fileName = new String(fileName.getBytes(),"ISO8859-1");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
response.setContentType("application/octet-stream;charset=ISO8859-1");
response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
response.addHeader("Pargam", "no-cache");
response.addHeader("Cache-Control", "no-cache");
} catch (Exception ex) {
ex.printStackTrace();
}
}

以上就是使用poi往execl表中写入数据的两种方式,需要注意的是,前端过来的请求不能是ajax请求,因为ajax无法解析二进制流的输出。具体原因客参考:https://www.cnblogs.com/houqx/p/10106562.html

Java下载execl表格的更多相关文章

  1. Java读取Execl表格数据

    在前面提到用java代码新建一个Execl 表格并添加数据到表格中, 这次写了一个读取Execl表格数据并添加导数据库中的案列 给定对方一个Execl模板表格,如果导入的Execl表格和预订的表格不相 ...

  2. java利用poi来读取execl表格返回对象

    利用poi来读取execl表格,返回一个对象(可能有点不完善,但是应该能满足平常的所用),用到了反射等等; 使用的jar包有: commons-collections4-4.1.jar poi-3.1 ...

  3. java的excel表格的导出与下载

    今天做一个java对excel表格的导出和下载的时候,从网络上搜寻了下载的模板,代码如下: 控制层: @RequestMapping(value = "excelOut_identifier ...

  4. java用jxl实现导出execl表格

    //先将需要导出的数据放到list中 //然后将list中的数据放到execl表中 @RequestMapping(params="exportExecl") public Str ...

  5. ajax请求下载Execl表

    Execl表是经常要用到的存放二位数据的表格,Java也可以直接操作Execl表,经常用到的方式就是jxl和poi. 在这次项目中,我用到的poi往Execl中写数据,刚开始设计的是前端发送一个aja ...

  6. 如何轻松的把图片导入execl表格中

    在项目中有时候会遇到往数据库中导数据的时候,往往需要把图片也一起导入execl表格中,那怎么才能把图片一块导入至execl中呢?那么今天我们就来看看怎么实现吧! 如何实现?今天我们就来用jxl和poi ...

  7. java下载安装,环境变量,hello world

    1.Java下载安装 网址:http://java.sun.com/javase/downloads/index.jsp win7 64位选择jdk-8u11-windows-x64.exe. 2.环 ...

  8. java导出excel表格

    java导出excel表格: 1.导入jar包 <dependency> <groupId>org.apache.poi</groupId> <artifac ...

  9. Java读取excel表格

    Java读取excel表格 一般都是用poi技术去读取excel表格的,但是这个技术又是什么呢 什么是Apache POI? Apache POI是一种流行的API,它允许程序员使用Java程序创建, ...

随机推荐

  1. ionic 2.x 3.x项目结构解析

    myApp │ config.xml //项目配置文件,包名.名称.minSdkVersion等都在此处配置 │ ionic.config.json │ package.json //项目依赖文件列表 ...

  2. [leetcode.com]算法题目 - Maximum Subarray

    Find the contiguous subarray within an array (containing at least one number) which has the largest ...

  3. 阻止事件冒泡,阻止默认事件,event.stopPropagation()和event.preventDefault(),return false的区别

    1.event.stopPropagation()方法 这是阻止事件的冒泡方法,不让事件向documen上蔓延,但是默认事件任然会执行,当你掉用这个方法的时候,如果点击一个连接,这个连接仍然会被打开, ...

  4. Atom 清空残余数据

    rm -rf ~/.atom rm /usr/local/bin/atom rm /usr/local/bin/apm rm ~/Library/Preferences/com.github.atom ...

  5. ubuntu下nodejs源码安装

    1.从github选择下载自己要安装的nodejs版本,https://github.com/nodejs/node/releases,我下载的版本是node-9.11.2.tar.gz 2.解压no ...

  6. Mac OSX配置XAMP虚拟主机

    在前端工作中,有时候需要配置下环境,这篇文章主要是记录了在wamp中配置虚拟主机 首先需要下载wamp软件和navicat数据库管理软件进行管理,下面默认已经下载好所需软件.并且打开服务. 第一步:把 ...

  7. 将celery定时任务设置为根据本地时区触发

    默认celery的时区为UTC,如果要在django项目中将celery定时任务配置为根据本地时区触发,则需要修改 在setttings.py 添加以下任意一行: # celery 相关配置 CELE ...

  8. C#实现程序的版本升级更新

    我们做了程序,不免会有版本升级,这就需要程序有自动版本升级的功能.那么看看我是如何实现程序自动更新的. 直接上代码: using System; using System.Collections.Ge ...

  9. Dell R730服务器 Raid5配置

    Dell R730服务器,有7块5t硬盘,默认做的RAID5.我们的目的是取其中6块硬盘做RAID5,留一块硬盘做热备. 一块SSD系统盘. 在这里,我具体解释一下 ①6块硬盘做成RAID5 ②6块硬 ...

  10. One difference between AngularJS' $location and window.location

    Recenently, I encountered a problem. Client side code is: $http({ url: "/api/runtimelicense&quo ...