java程序中 poi导出excel/csv导出excel 超详细代码!!!!
程序员文章站
2024-03-21 12:53:22
...
在最近接到的需求当中要求把生成列表的数据,导出excel表格,这个问题并不难解决。在这里给大家介绍两种方法:poi和csv
首先介绍poi:
首先先导入依赖:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
想了解poi如何使用,请查看官方文档!
详细代码如下:(支持分sheet操作)
注意我生成的是xls文件格式。
在这里我导出的是多sheet表格,可以按照自己的开发需求随意删减。
String fileName = "文件名" + new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
String url = path + fileName + ".xls";
List<Class> list = null;
List<Student> studentList = null;
查询list的方法,根据自己的业务逻辑进行实现。
//数据
List<String[]> dataset = new ArrayList<String[]>();
for (int i = 0; i < list.size(); i++) {
String[] arr = new String[4];
arr[0] = list.get(i).getId() == null ? "" : list.get(i).getId().toString();
arr[1] = list.get(i).getMonth() == null ? "" : list.get(i).getMonth();
arr[3] = list.get(i).getType() == null ? "" : list.get(i).getProvisionType();
dataset.add(arr);
}
//数据
List<String[]> dataset2 = new ArrayList<String[]>();
for (int i = 0; i < studentList .size(); i++) {
String[] arr2 = new String[2];
arr2[0] = studentList .get(i).getContractNo() == null ? "" : studentList .get(i).getContractNo();
arr2[1] = studentList .get(i).getName() == null ? "" : studentList .get(i).getName();
dataset2.add(arr2);
}
//设置表头
String[] handers1 = {"表头1","表头2","表头3","表头4"};
String[] handers2 = {"表头1", "表头2", "表头3"};
//对象
ExcelExp e1 = new ExcelExp("第一个sheet名称", handers1, dataset);
ExcelExp e2 = new ExcelExp("第二个sheet名称", handers2, dataset2);
List<ExcelExp> mysheet = new ArrayList<ExcelExp>();
mysheet.add(e1);
mysheet.add(e2);
ExcelExportUtil.exportManySheetExcel(url, mysheet); //生成sheet 这也是生成excel的方法.
super.download(url, response);//导出
// 删除临时文件
File file = new File(url);
BASE64FileUtils.deleteFile(file);
public class ExcelExp{
private String fileName;// sheet的名称
private String[] handers;// sheet里的标题
private List<String[]> dataset;// sheet里的数据集
public ExcelExp(String fileName, String[] handers, List<String[]> dataset) {
this.fileName = fileName;
this.handers = handers;
this.dataset = dataset;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String[] getHanders() {
return handers;
}
public void setHanders(String[] handers) {
this.handers = handers;
}
public List<String[]> getDataset() {
return dataset;
}
public void setDataset(List<String[]> dataset) {
this.dataset = dataset;
}
}
public class ExcelExportUtil {
/**
* @param @param file 导出文件路径
* @param @param mysheets
* @return void
* @throws
* @Title: exportManySheetExcel
* @Description: 可生成单个、多个sheet
*/
public static void exportManySheetExcel(String file, List<ExcelExp> mysheets) {
HSSFWorkbook wb = new HSSFWorkbook();//创建工作薄
List<ExcelExp> sheets = mysheets;
//表头样式
HSSFCellStyle style = wb.createCellStyle();
//字体样式
HSSFFont fontStyle = wb.createFont();
fontStyle.setFontName("微软雅黑");
fontStyle.setFontHeightInPoints((short) 12);
style.setFont(fontStyle);
for (ExcelExp excel : sheets) {
//新建一个sheet
HSSFSheet sheet = wb.createSheet(excel.getFileName());//获取该sheet名称
String[] handers = excel.getHanders();//获取sheet的标题名
HSSFRow rowFirst = sheet.createRow(0);//第一个sheet的第一行为标题
//写标题
for (int i = 0; i < handers.length; i++) {
//获取第一行的每个单元格
HSSFCell cell = rowFirst.createCell(i);
//往单元格里写数据
cell.setCellValue(handers[i]);
cell.setCellStyle(style); //加样式
sheet.setColumnWidth(i, 4000); //设置每列的列宽
}
//写数据集
List<String[]> dataset = excel.getDataset();
for (int i = 0; i < dataset.size(); i++) {
String[] data = dataset.get(i);//获取该对象
//创建数据行
HSSFRow row = sheet.createRow(i + 1);
for (int j = 0; j < data.length; j++) {
//设置对应单元格的值
row.createCell(j).setCellValue(data[j]);
}
}
}
// 写文件
try {
FileOutputStream out = new FileOutputStream(new File(file));
out.flush();
wb.write(out);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class super {
public boolean download(String path, HttpServletResponse response) throws BizException {
if (null == path) {
log.info("download path is null");
throw new BizException(BizCode.Commend_40001004);
}
File file = new File(path);
if (!file.exists()) {
throw new BizException(BizCode.Commend_40001004);
}
try (OutputStream out = response.getOutputStream(); FileInputStream is = new FileInputStream(file);) {
response.setHeader("Content-Type", "application/force-download");
response.setHeader("Content-Disposition",
"attachment;filename=" + URLEncoder.encode(file.getName(), "UTF-8"));
byte[] buf = new byte[1024];
int read = 0;
while ((read = is.read(buf, 0, 1024)) != -1) {
out.write(buf, 0, read);
}
} catch (Exception e) {
throw new BizException(BizCode.Commend_40001005);
}
return true;
}
}
public class BASE64FileUtils {
public static void deleteFile(File file) {
if (!file.exists())
return;
if (file.isDirectory()) {
File[] listFiles = file.listFiles();
for (File file2 : listFiles) {
deleteFile(file2);
}
file.delete();
} else {
file.delete();
}
}
}
-------------------------------------------------------------------------------------------------------------------------
好了,现在再给大家介绍一下csv文件导出。
还是得先导入依赖:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-csv</artifactId>
<version>1.2</version>
</dependency>
前面的流程大致相同,在这就不在写一遍了。
List<Student>list=null;
// 文件名
String filename = "文件名" + new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + ".csv";
// CSV文件每一列的名称
String[] colNames = { "表头1","表头2","表头3","表头4" };
File file=new File(filename);
CSVFormat csvFormat = CSVFormat.DEFAULT.withHeader(colNames);
try (OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
CSVPrinter csvPrinter = new CSVPrinter(osw, csvFormat);) {
for (Student student:list){
csvPrinter.printRecord(student.getName(),student.getId());
}
csvPrinter.flush();
}catch(IOException e){
e.printStackTrace();
}
CSVUtils.exportCSVFile(response, file);
file.delete();
public class CSVUtils {
/**
* 导出文件
*
* @param response
* @param file
*/
public static void exportCSVFile(HttpServletResponse response, File file) {
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(file);
int len = 0;
byte[] buffer = new byte[1024];
out = response.getOutputStream();
response.reset();
// 设置此response为文件下载响应
response.setContentType("application/csv;charset=UTF-8");
response.setHeader("Content-Disposition",
"attachment; filename=" + URLEncoder.encode(file.getName(), "UTF-8"));
response.setCharacterEncoding("UTF-8");
// 先写UTF-8文件标志头
out.write(new byte[] { (byte) 0xEF, (byte) 0xBB, (byte) 0xBF });
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
out.flush();
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
try {
in.close();
out.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
如果导出的文件里面存在double类型的值,在导出的时候会存在一个问题,由于数值过大,在导出的时候你的值会变成科学计数法。
具体的解决办法可以查看上一篇博客
double类型字数过长变成科学计数法
编写不易!转载请标明出处。
上一篇: 文件筛选库(按照某固定类型筛选)
下一篇: 编程书籍大全 博客分类: 编程书籍 编程
推荐阅读
-
java程序中 poi导出excel/csv导出excel 超详细代码!!!!
-
javaweb中如何使用POI把数据导出为Excel(有下载提示框)详细教程
-
springboot框架中-java实现Excel、csv、txt 文件的批量导出数据-亲手实测(二)-csv & txt
-
Java利用POI实现导入导出Excel表格示例代码
-
Java利用POI实现导入导出Excel表格示例代码
-
java poi导出图片到excel示例代码
-
java poi导出图片到excel示例代码
-
Java自定义注解以及在POI导出EXCEL中的一个应用 javaannotationPOIexcel
-
Java使用Apache.POI中HSSFWorkbook导出到Excel的实现方法
-
详细介绍java实现合并单元格的同时并导出excel示例代码