无需引入依赖,使用的是org.apache.poi
遇到的一些问题:
1、下载的excel文件为zip
zip文件目录如下,修改后缀为xls后为正确的表格
解决方法,加上配置信息或者renderBinary方法加上文件名称
我做的是访问接口后直接下载文件,下载结果:
执行代码:
package controllers;
import com.alibaba.fastjson2.JSON;
import models.mongodb_biddata.MysqlEnterprisesQichacha;
import okhttp3.*;
import org.apache.http.client.methods.HttpGet;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import play.Logger;
import play.libs.WS;
import play.mvc.Controller;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;
/**
* @Author: ZD
* @Date: 2023/7/27
*/
public class ExcelUploading extends Controller {
private static final String file_path = "C:\\guoxin\\mongodb-mysql/";
public void getExcel() {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
File exportFile = null;
FileInputStream fileInputStream = null;
XSSFWorkbook workbook = new XSSFWorkbook();
//查询出要插入excel的数据
List<MysqlEnterprisesQichacha> mysqlEnterprisesQichachaList = MysqlEnterprisesQichacha.find("").fetch(10);
String fileName = "test";
try {
XSSFSheet sheet = workbook.createSheet();
// 创建头部信息行和单元格
XSSFRow headerRow = sheet.createRow(0);
headerRow.createCell(0).setCellValue("标题");
headerRow.createCell(1).setCellValue("行业");
headerRow.createCell(2).setCellValue("地区");
headerRow.createCell(3).setCellValue("类型");
headerRow.createCell(4).setCellValue("发布时间");
headerRow.createCell(5).setCellValue("链接");
headerRow.createCell(6).setCellValue("正文");
mysqlEnterprisesQichachaList.stream().forEach(mysqlEnterprisesQichacha -> {
XSSFRow dataRow = sheet.createRow(mysqlEnterprisesQichachaList.indexOf(mysqlEnterprisesQichacha)+1);
dataRow.createCell(0).setCellValue(mysqlEnterprisesQichacha.getId_zbw());
dataRow.createCell(1).setCellValue(mysqlEnterprisesQichacha.getComid_zbw());
dataRow.createCell(2).setCellValue(mysqlEnterprisesQichacha.getComname());
dataRow.createCell(3).setCellValue(mysqlEnterprisesQichacha.getCreate_time());
dataRow.createCell(4).setCellValue(mysqlEnterprisesQichacha.getResult());
dataRow.createCell(5).setCellValue(mysqlEnterprisesQichacha.getResult());
dataRow.createCell(6).setCellValue(mysqlEnterprisesQichacha.getResult());
});
//写入表格数据
workbook.write(byteArrayOutputStream);
exportFile = new File(file_path + "app/controllers/"+fileName+".xlsx");
if (!exportFile.exists()) {
exportFile.createNewFile();
}
FileOutputStream fileOut = new FileOutputStream(exportFile);
fileOut.write(byteArrayOutputStream.toByteArray());
fileOut.close();
fileInputStream = new FileInputStream(exportFile);
} catch (IOException e) {
Logger.info("文件转换异常:{}", e);
}
//如果导出文件为zip,可以加上以下注释代码,当renderBinary方法没有添加name参数时需要加上
// response.setContentTypeIfNotSet("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
renderBinary(fileInputStream,fileName+".xls");
}
}
我在文件上传后某个空间,然后再进行下载时出现了zip问题未解决!!!