前端js
function downloadGet(url) {
let xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = "blob";
xhr.onload = function () {
if (this.status === 200) {
let blob = this.response;
let reader = new FileReader();
reader.readAsDataURL(blob);
reader.onload = function (e) {
let a = document.createElement('a');
a.download = 'topology_report.xls';
a.href = e.target.result;
$("body").append(a);
a.click();
$(a).remove();
}
}
};
xhr.send();
}
后台java代码:
private static final String sheetName = "sheet";
public static <T> String convert(List<T> list, String rootPath, String filePath, String excelName, HttpServletResponse response) {
if (list == null || list.isEmpty()) {
return null;
}
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet(sheetName);
Field[] fs = list.get(0).getClass().getDeclaredFields();
int len = fs.length;
List<Field> fieldList = null;
List<String> titleList = null;
PoiExcelColumn column;
for (Field f : fs) {
column = f.getAnnotation(PoiExcelColumn.class);
if (column != null) {
if (fieldList == null) {
fieldList = new ArrayList<>(len);
}
f.setAccessible(true);
fieldList.add(f);
if (titleList == null) {
titleList = new ArrayList<>(len);
}
titleList.add(column.value());
}
}
if (titleList == null) {
return null;
}
int rowIdx = 0, colSum = titleList.size();
HSSFRow row = sheet.createRow(rowIdx++);
HSSFCell cell;
for (int i = 0; i < colSum; i++) {
cell = row.createCell(i);
cell.setCellValue(titleList.get(i));
}
Object obj;
String value;
FileOutputStream fos = null;
InputStream is = null;
OutputStream os = null;
try {
for (T t : list) {
row = sheet.createRow(rowIdx++);
for (int i = 0; i < colSum; i++) {
obj = fieldList.get(i).get(t);
value = obj == null ? "" : obj.toString();
cell = row.createCell(i);
cell.setCellValue(value);
}
}
String downFilePath = rootPath + filePath;
File f = new File(downFilePath);
if (f.exists()) {
f.delete();
}
fos = new FileOutputStream(downFilePath);
sheet.setGridsPrinted(true);
HSSFFooter footer = sheet.getFooter();
footer.setRight("Page " + HSSFFooter.page() + " of " + HSSFFooter.numPages());
workbook.write(fos);
// 按流下载数据
// 下载到IE客户端
// 解决中文乱码问题,设置后产生一个新的String对象此对象以改变了编码
String newPath = URLEncoder.encode(excelName, "utf-8");
// 在页面上弹出一个下在窗口指定下载文件保存的文件类型
response.setContentType("application/vnd.ms-excel");
// 设置报头信息,弹出窗口中显示的文件名
response.setHeader("Content-Disposition", "attachment; filename=" + newPath);
is = new FileInputStream(downFilePath);
os = response.getOutputStream();
// 具体的输入输出流操作
byte[] b = new byte[1024 * 8];
int i = 0;
while ((i = is.read(b)) != -1) {
os.write(b, 0, i);
i = 0;
}
os.flush();
return filePath + excelName;
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fos.close();
os.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}