JXT 导出数据到EXCEL
郏景澄
2023-12-01
1.
public class ExportExcel {
/**
* @param List封装着Object[]的列表
* @param title每个sheet里的标题 */
private final static Logger log = Logger.getLogger(ExportExcel.class.getName());
public static InputStream getExcelInputStream(List<String[]> list, String[] title) {
ByteArrayOutputStream out = new ByteArrayOutputStream();// 将OutputStream转化为InputStream
writeExcel(out, list, title);
return new ByteArrayInputStream(out.toByteArray());
}
public static void writeExcel(OutputStream out, List<String[]> list, String[] title) {
try {
WritableWorkbook workbook = Workbook.createWorkbook(out);
WritableSheet ws = workbook.createSheet("sheet 1", 0);
int rowNum = 0; // 要写的行,第一行是从0开始,以此类推
if (title != null) {
putRow(ws, 0, title);
rowNum = 1;
}
for (int i = 0; i < list.size(); i++, rowNum++) { //数据写入Excel
Object[] cells = (Object[]) list.get(i);
putRow(ws, rowNum, cells);
}
workbook.write();
workbook.close();
} catch (RowsExceededException e) {
log.error(e);
} catch (WriteException e) {
log.error(e);
} catch (IOException e) {
log.error(e);
}
}
private static void putRow(WritableSheet ws, int rowNum, Object[] cells)
throws RowsExceededException, WriteException {
for (int j = 0; j < cells.length; j++) {
Label cell = new Label(j, rowNum, "" + cells[j]);
ws.addCell(cell);
}
}
}
2. SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
excelName = "Products_Export_"+ df.format(new java.util.Date()) + ".xls";//导出Excel文件名
List<InventoryTotalVO> rowList=pageBean.getRows();//导出的记录
List<String[]> extelDataList=new ArrayList<String[]>();
for(int i=0;i<rowList.size();i++){
extelDataList.add(data);//要写入Excel的数据
}
String[] title = { };//Excel标题
excelStream=ExportExcel.getExcelInputStream(extelDataList,title);
3>
<result name="excel" type="stream">
<param name="contentType">
application/vnd.ms-excel
</param>
<param name="inputName">excelStream</param>
<param name="contentDisposition">
attachment;filename="${excelName}"
</param>
<param name="bufferSize">1024</param>
</result>
<param name="inputPath">\download</param><!--下载文件的保存路径 -->
<param name="maxRows">1000</param><!-- 下载文件的行数-->
</action>