1.使用POI

引入jar包

<!-- poi HSSF is our port of the Microsoft Excel 97(-2007) file format (BIFF8) to pure Java. -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<!-- poi-ooxml XSSF is our port of the Microsoft Excel XML (2007+) file format (OOXML) to pure Java -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.17</version>
</dependency>

  

ExcelExport.java

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List; /**
* @author Sue
* @create 2019-04-29 14:38
**/
@Controller
public class ExcelExport { @RequestMapping(value = "/execute", method = RequestMethod.GET)
public void execute(HttpServletRequest request, HttpServletResponse response) throws IOException { //待导出的数据
List<ReportInfo> reportInfoList = new ArrayList<>();
reportInfoList.add(new ReportInfo("上海卡部", "this week 01", "next week 01"));
reportInfoList.add(new ReportInfo("广州卡部", "this week 05", "next week 05"));
reportInfoList.add(new ReportInfo("厦门卡部", "this week 05", "next week 05"));
reportInfoList.add(new ReportInfo("宁波卡部", "this week 05", "next week 05"));
reportInfoList.add(new ReportInfo("武汉卡部", "this week 05", "next week 05")); // 导出.xlsx文件使用这个对象
// XSSFWorkbook work = null; HSSFWorkbook workbook = null;
try {
//创建一个空白的workbook
workbook = new HSSFWorkbook();
//建立新的sheet对象(excel的表单)
HSSFSheet sheet = workbook.createSheet("周报信息表");
//在sheet里创建第一行,参数为行索引(excel的行),可以是0~65535之间的任何一个
HSSFRow row1 = sheet.createRow(0);
//创建单元格(excel的单元格,参数为列索引,可以是0~255之间的任何一个
HSSFCell cell = row1.createCell(0); //创建样式
HSSFCellStyle cellStyle = workbook.createCellStyle();
//水平居中
cellStyle.setAlignment(HorizontalAlignment.CENTER);
//垂直居中
cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
//设置单元格样式
cell.setCellStyle(cellStyle);
//设置单元格内容
cell.setCellValue("周报信息一览表");
//合并单元格CellRangeAddress构造参数依次表示起始行,截至行,起始列, 截至列
sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 3));
//在sheet里创建第二行
HSSFRow row2 = sheet.createRow(1);
//创建单元格并设置单元格内容
row2.createCell(0).setCellValue("业务条线");
row2.createCell(1).setCellValue("本周工作成果");
row2.createCell(2).setCellValue("下周工作计划");
//在sheet里创建第三行
HSSFCellStyle cellStyle1 = workbook.createCellStyle();
//自动换行
cellStyle1.setWrapText(true);
for (int i = 0; i < reportInfoList.size(); i++) {
HSSFRow row = sheet.createRow(2 + i); HSSFCell cell0 = row.createCell(0);
cell0.setCellStyle(cellStyle1);
cell0.setCellValue(reportInfoList.get(i).getName()); HSSFCell cell1 = row.createCell(1);
cell1.setCellStyle(cellStyle1);
cell1.setCellValue(reportInfoList.get(i).getThisWeek()); HSSFCell cell2 = row.createCell(2);
cell2.setCellStyle(cellStyle1);
cell2.setCellValue(reportInfoList.get(i).getNextWeek());
}
//输出Excel文件
response.reset();
response.setContentType("application/octet-stream;charset=utf-8");
String fileName = "周报信息导出表" + ".xls";
OutputStream os = response.getOutputStream();
response.reset();//清空输出流
String finalFileName = URLEncoder.encode(fileName, "UTF8");
//这里设置一下让浏览器弹出下载提示框,而不是直接在浏览器中打开
response.setHeader("Content-Disposition", "attachment; filename=\"" + finalFileName + "\"");
response.setContentType("application/vnd.ms-excel");
workbook.write(os);
os.close();
} catch (IOException e) {
throw new IOException();
} finally {
if (workbook != null) {
workbook.close();
}
}
}
}

ReportInfo.java

/**
* @author Sue
* @create 2019-04-29 14:47
**/
public class ReportInfo {
private String name;
private String thisWeek;
private String nextWeek; public ReportInfo(String name, String thisWeek, String nextWeek) {
this.name = name;
this.thisWeek = thisWeek;
this.nextWeek = nextWeek;
} public ReportInfo() { } public String getName() { return name;
} public void setName(String name) {
this.name = name;
} public String getThisWeek() {
return thisWeek;
} public void setThisWeek(String thisWeek) {
this.thisWeek = thisWeek;
} public String getNextWeek() {
return nextWeek;
} public void setNextWeek(String nextWeek) {
this.nextWeek = nextWeek;
}
}

访问IP测试

2.使用JXL

引入jar包

<!-- https://mvnrepository.com/artifact/net.sourceforge.jexcelapi/jxl -->
<dependency>
<groupId>net.sourceforge.jexcelapi</groupId>
<artifactId>jxl</artifactId>
<version>2.6.12</version>
</dependency>

TestExcel.java

import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.VerticalAlignment;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.JxlWriteException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController; import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List; /**
* @author Sue
* @create 2019-04-29 10:39
**/
@RestController
public class TestExcel { /**
* 测试 导出xls文件的表头
*/
public static final String[] TestToXls = {"编号", "设计人员工号", "设计人员姓名", "开发人员工号", "开发人员姓名", "测试人员工号", "测试人员姓名"}; @GetMapping("/test")
public void toExcel(HttpServletResponse response, HttpServletRequest request) throws Exception { List<Test> listTest = new ArrayList<Test>();
Test test = new Test("1", "01", "001", "0001", "00001", "000001", "0000001");
listTest.add(test); //这里为导出文件存放的路径
String filePath = "D:\\sheet\\";
//加入一个uuid随机数是因为
//每次导出的时候,如果文件存在了,会将其覆盖掉,这里是保存所有的文件
File file = new File(filePath);
if (!file.exists()) {
file.mkdirs();
} SimpleDateFormat fmt = new SimpleDateFormat("yyyy年MM月dd HH时mm分ss秒");
// 给要导出的文件起名为 "测试导出数据表_时间.xls"
String filePath2 = filePath + "数据表" + "-" + fmt.format(new Date()) + ".xls";
WritableWorkbook wb = null;
try {
File file2 = new File(filePath2);
if (!file2.exists()) {//不存在,创建
file2.createNewFile();
}
wb = Workbook.createWorkbook(file2);//创建xls表格文件 // 表头显示
WritableCellFormat wcf = new WritableCellFormat();
wcf.setAlignment(Alignment.CENTRE);// 水平居中
wcf.setWrap(true);
wcf.setVerticalAlignment(VerticalAlignment.CENTRE);// 垂直居中
wcf.setFont(new WritableFont(WritableFont.TIMES, 13, WritableFont.BOLD));// 表头字体 加粗 13号
wcf.setBackground(jxl.format.Colour.PERIWINKLE);
// 内容显示
WritableCellFormat wcf2 = new WritableCellFormat();
wcf2.setWrap(true);//设置单元格可以换行
wcf2.setAlignment(Alignment.CENTRE);//水平居中
wcf2.setVerticalAlignment(VerticalAlignment.CENTRE);// 垂直居中
wcf2.setFont(new WritableFont(WritableFont.TIMES, 11));// 内容字体 11号 //导出的xls的第一页,第二页就是0换成1,“sheet1”,也可以修改为自己想要的显示的内容
WritableSheet ws = wb.createSheet("sheet1", 0);
//WritableSheet ws2 = wb.createSheet("sheet2", 1);//第2个sheet页
ws.addCell(new Label(0, 0, "导出结果"));//代表着表格中第一列的第一行显示查询结果几个字 // 导出时生成表头
for (int i = 0; i < TestToXls.length; i++) {
//i,代表的第几列,1,代表第2行,第三个参数为要显示的内容,第四个参数,为内容格式设置(按照wcf的格式显示)
ws.addCell(new Label(i, 1, TestToXls[i], wcf));//在sheet1中循环加入表头
} int k = 2;//从第三行开始写入数据 for (int i = 0; i < listTest.size(); i++) {
ws.addCell(new Label(0, k, listTest.get(i).getIdd(), wcf2));
ws.addCell(new Label(1, k, listTest.get(i).getDesignId(), wcf2));
ws.addCell(new Label(2, k, listTest.get(i).getDesignName(), wcf2));
ws.addCell(new Label(3, k, listTest.get(i).getDevelopId(), wcf2));
ws.addCell(new Label(4, k, listTest.get(i).getDevelopName(), wcf2));
ws.addCell(new Label(5, k, listTest.get(i).getTestId(), wcf2));
ws.addCell(new Label(6, k, listTest.get(i).getTestName(), wcf2));
//ws.mergeCells(4, 5, 5, 5);//合并两列,按参数顺序,意思是第4列的第五行,跟第五列的第五行合并为一个单元格
k++;
}
wb.write();//写入,到这里已经生成完成,可以在相应目录下找到刚才生成的文件
} catch (IOException e) {
e.printStackTrace();
} catch (JxlWriteException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
} finally {
try {
if (wb != null) {
wb.close();
}
} catch (WriteException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//这个是我们项目中,是把刚才生成的文件,响应到前台,进行下载、保存,可省略。
downLoadFile(filePath2, response);
} public void downLoadFile(String filePath, HttpServletResponse response) {
SimpleDateFormat fmt = new SimpleDateFormat("yyyy年MM月dd HH时mm分ss秒"); FileInputStream in = null;
ServletOutputStream out = null;
BufferedOutputStream toOut = null;
String fileName = "导出数据表" + "-" + fmt.format(new Date()) + ".xls";
try {
in = new FileInputStream(new File(filePath));
byte[] buffer = new byte[in.available()];
while (in.read(buffer) != -1) {
// HttpServletResponse response = this.getContext().getResponse();//从application中得到response
response.reset();// 清空
// 设置响应的文件的头文件格式
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("UTF-8"), "iso-8859-1"));
// response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("GBK"), "ISO8859-1"));
response.addHeader("Content-type", "application-download");
// 获取响应的对象流
out = response.getOutputStream();
toOut = new BufferedOutputStream(out);
toOut.write(buffer);
toOut.flush();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
if (toOut != null) {
toOut.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
} }

Test.java

/**
* @author Sue
* @create 2019-04-29 10:41
**/
public class Test {
private String idd;//编号
private String designId;//设计人员工号
private String designName;//设计人员姓名
private String developId;//开发人员工号
private String developName;//开发人员姓名
private String testId;//测试人员工号
private String testName;//测试人员姓名 public Test(String idd, String designId, String designName, String developId, String developName, String testId, String testName) {
this.idd = idd;
this.designId = designId;
this.designName = designName;
this.developId = developId;
this.developName = developName;
this.testId = testId;
this.testName = testName;
} public Test() { } public String getIdd() {
return idd;
} public void setIdd(String idd) {
this.idd = idd;
} public String getDesignId() {
return designId;
} public void setDesignId(String designId) {
this.designId = designId;
} public String getDesignName() {
return designName;
} public void setDesignName(String designName) {
this.designName = designName;
} public String getDevelopId() {
return developId;
} public void setDevelopId(String developId) {
this.developId = developId;
} public String getDevelopName() {
return developName;
} public void setDevelopName(String developName) {
this.developName = developName;
} public String getTestId() {
return testId;
} public void setTestId(String testId) {
this.testId = testId;
} public String getTestName() {
return testName;
} public void setTestName(String testName) {
this.testName = testName;
}
}

访问IP测试即可

分别使用POI和JXL导出数据到Excel的更多相关文章

  1. jxl 导出数据到excel

    优点: Jxl对中文支持非常好,操作简单,方法看名知意. Jxl是纯javaAPI,在跨平台上表现的非常完美,代码可以再windows或者Linux上运行而无需重新编写 支持Excel 95-2000 ...

  2. 用jxl导出数据到excel

    需要jxl.jar 测试结果没问题,代码: package com; import java.io.File; import java.io.IOException; import java.util ...

  3. JXL 读取 Excel java中jxl导出数据到excel的例子 上传文件

    2010-10-14 19:17:06 com.opensymphony.xwork2.util.logging.commons.CommonsLogger info 信息: Entferne Dat ...

  4. 从数据库导出数据到excel之POI操作

    项目说明: 1:数据库中有两张表,主键关联 2:根据条件查询数据 3:处理为需要的数据封装类型,然后传到导出excel的方法中 <--框架部署就不详谈了,用的spring框架--> 补充: ...

  5. Java操作Jxl实现导出数据生成Excel表格数据文件

    实现:前台用的框架是Easyui+Bootstrap结合使用,需要引入相应的Js.Css文件.页面:Jsp.拦截请求:Servlet.逻辑处理:ClassBean.数据库:SQLserver. 注意: ...

  6. NPOI导出数据到Excel

    NPOI导出数据到Excel   前言 Asp.net操作Excel已经是老生长谈的事情了,可下面我说的这个NPOI操作Excel,应该是最好的方案了,没有之一,使用NPOI能够帮助开发者在没有安装微 ...

  7. 一个方便且通用的导出数据到 Excel 的类库

    一个方便且通用的导出数据到 Excel 的类库 起源: 之前在做一个项目时,客户提出了许多的导出数据的需求: 导出用户信息 导出业务实体信息 各种查询都要能导出 导出的数据要和界面上看到的一致 可以分 ...

  8. 从数据库导出数据到excel之List<List<Object>>导出

    说明:有时候数据处理为List<List<Object>>更方便 姊妹篇:从数据库导出数据到excel之List<Map<>>导出 兄弟篇:从数据库导出 ...

  9. java代码导出数据到Excel、js导出数据到Excel(三)

     jsp内容忽略,仅写个出发按钮:          <button style="width: 100px" onclick="expertExcel()&quo ...

随机推荐

  1. MySQL 笔记整理(19) --为什么我只查一行的语句,也执行这么慢?

    笔记记录自林晓斌(丁奇)老师的<MySQL实战45讲> (本篇内图片均来自丁奇老师的讲解,如有侵权,请联系我删除) 19) --为什么我只查一行的语句,也执行这么慢? 需要说明一下,如果M ...

  2. nginx系列6:nginx的进程结构

    nginx的进程结构 如下图: 通过ps –ef | grep nginx可以看到共有三个进程,一个master进程,两个worker进程. nginx是多进程结构,多进程结构设计是为了保证nginx ...

  3. vue中使用provide和inject刷新当前路由(页面)

    1.场景 在处理列表时,常常有删除一条数据或者新增数据之后需要重新刷新当前页面的需求. 2.遇到的问题 1. 用vue-router重新路由到当前页面,页面是不进行刷新的 2.采用window.rel ...

  4. win10 64位IIS链接32位ACCESS数据库

    window10中IIS运行.asp文件链接数据库时出现错误,显示“An error occurred on the server when processing the URL. Please co ...

  5. Dart语言入门(一)

    Dart 语言介绍 Dart 是谷歌在 2011 年推出的编程语言,是一种结构化 Web 编程语言,允许用户通过 Chromium 中所整合的虚拟机(Dart VM)直接运行 Dart 语言编写的程序 ...

  6. dotnet core如何编译exe

    dotnet core 有一个转变,他用dll格式来代替exe作为通用执行格式,然后要命令行dotnet yourApp.dll 来运行程序.为了提高逼格,双击可以运行,可以采用以下方案: 方案一 用 ...

  7. C# ToString()日期格式

    C# ToString()日期格式 ToString:2016/9/27 0:00:00ToString("yyyy/MM/dd"):2016/09/27ToString(&quo ...

  8. JS倒计时两种种实现方式

    最近做浏览器界面倒计时,用js就实现,两种方式: 一:设置时长,进行倒计时.比如考试时间等等 代码如下: <html> <head> <meta charset=&quo ...

  9. 解决vs2017不能添加引用问题

    c# 添加引用时报错:“未能正确加载“ReferenceManagerPackage”包”的解决方法 在添加应用的时候,右键点击“引用”,选择“添加引用”后,会提示“**未能正确加载Reference ...

  10. 用css 添加手状样式,鼠标移上去变小手,变小手

    用css 添加手状样式,鼠标移上去变小手,变小手 cursor:pointer; 用JS使鼠标变小手onmouseover(鼠标越过的时候) onmouseover="this.style. ...