生成Excel并下载
程序员文章站
2024-03-20 17:53:52
...
一、后端代码
1、接口 classificationResultExportXls.action
/**
* 导出Excel
* @return
*/
public String classificationResultExportXls(HttpServletResponse response) {
try {
List<ClassificationResultVO> list = houseClassificationService.classificationResultQuery();
response.setContentType(
"application/octet-stream;charset=GB2312");
String FileName = DateUtils.dateToString(
DateUtils.getCurrentDate(), DateUtils.yyyy_MM_dd) + ".xls";
response.setHeader("Content-Disposition",
"attachment; filename=\"" + FileName + "\"");
try {
String[] tiles = {"街道", "社区", "网格", "楼栋编码", "楼栋名称", "楼栋地址"};
List<String[]> contentList = new ArrayList<>();
for (ClassificationResultVO vo : list) {
String[] tmpList = new String[tiles.length];
tmpList[0] = vo.getJdName();
tmpList[1] = vo.getSqName();
tmpList[2] = vo.getWgName();
tmpList[3] = vo.getBuildCode();
tmpList[4] = vo.getName();
tmpList[5] = vo.getAddress();
contentList.add(tmpList);
}
ExcelUtils.write("楼栋信息", this.getResponse()
.getOutputStream(), tiles, contentList);
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e) {
setResultDefaultFail(e.getMessage());
logError(this.getClass(), e, e.getMessage());
}
return null;
}
2、ExcelUtils.write()
/**
* 读取Excel
*
* @param outputStream
* 输出流 *
* @param sheetName
* sheet名字
* @param tiles
* 输入参数,保存读取到的标题
* @param contentList
* 输入参数,保存读取到的内容
*/
public static void write(String sheetName, OutputStream outputStream,
String[] tiles, List<String[]> contentList)
{
ExcelWriter writer = new ExcelWriterDefaultImpl();
Map map = new HashMap();
map.put("sheetName", sheetName);
map.put("titles", tiles);
map.put("contentList", contentList);
writer.write(outputStream, map);
}
2、ExcelWriter.write()
public void write(OutputStream outputStream, Map map)
{
try
{
setContent(map);
workbook.write(outputStream);
outputStream.flush();
outputStream.close();
}
catch (IOException e)
{
throw new RuntimeException(e);
}
finally
{
try
{
if (outputStream != null)
outputStream.close();
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
}
3、ExcelWriterByTempleExcelImpl.setContent(map)
public class ExcelWriterByTempleExcelImpl extends ExcelWriter {
@Override
protected void setContent(Map map) {
File templeExcelFile = (File) map.get("templeExcelFile");
List<String[]> dataContent = (List<String[]>) map.get("dataContent");
if (dataContent == null || dataContent.size() <= 0)
throw new NullPointerException();
HSSFWorkbook workbook = getHSSFWorkbookByTemple(templeExcelFile);
this.setWorkbook(workbook);
HSSFSheet sheet = workbook.getSheetAt(0);
int colNum = dataContent.get(0).length;
int rowNum = 0;
for (int i = 0; i < colNum; i++) {
sheet.setColumnWidth((short) i, (short) 5000);
}
// workbook.setSheetName(0, sheetName, HSSFWorkbook.ENCODING_UTF_16);
HSSFCellStyle normalStyle = workbook.createCellStyle();
setCellStyleFont(normalStyle, (short) 10, HSSFFont.BOLDWEIGHT_NORMAL,
HSSFColor.BLACK.index);
rowNum = sheet.getLastRowNum();
rowNum++;
HSSFRow row;
for (Iterator iterator = dataContent.iterator(); iterator.hasNext();) {
Object[] contents = (Object[]) iterator.next();
row = sheet.createRow((short) rowNum);
for (int i = 0; i < contents.length; i++) {
// HSSFRow row = sheet.createRow((short) rowNum);
HSSFCell cell = row.createCell((short) i);
cell.setCellStyle(normalStyle);
setCellValue(contents[i], cell);
}
rowNum++;
}
}
}
二、前端代码
1、jsp
<table>
<td align="center" style="width: 12%;">
<button οnclick="exportCurrentExcel()">导出当前页</button>
</td>
</table>
2、js
function exportCurrentExcel(){
var params = {};
//调用
DownLoadFile({
url:path+ '/page/xxcj/houseClassificationAction!classificationResultExportXls.action', //请求的url
data:params //要发送的参数
});
}
//用js生成一个form,用这个form提交参数,并返回“流”类型的数据。在实现过程中,页面也没有进行刷新。
var DownLoadFile = function (options) {
var config = $.extend(true, { method: 'post' }, options);
var $iframe = $('<iframe id="down-file-iframe" />');
var $form = $('<form target="down-file-iframe" method="' + config.method + '" />');
$form.attr('action', config.url);
for (var key in config.data) {
$form.append('<input type="hidden" name="' + key + '" value="' + config.data[key] + '" />');
}
$iframe.append($form);
$(document.body).append($iframe);
$form[0].submit();
$iframe.remove();
}