首页 技术 正文
技术 2022年11月12日
0 收藏 790 点赞 3,872 浏览 9648 个字

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

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,118
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,590
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,435
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,206
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,842
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,927