用Java导出为excel表格

时间:2023-03-08 22:40:31

导出的是最基础的excel表格,没有任何样式。

  <input type="button" value="输出到Excel" onclick='outputtable()' class="btn btn-info    margin-right-20"  style="width:80px;" />  

 <script>
function outputtable(){
url="outputAll.action"; 
window.open(url); }
</script>

在MVC的controller层中,写action

@RequestMapping("/outputEle.action")
public String queEle(HttpServletRequest request,
HttpServletResponse response, TableEle tableEle) throws Exception{
request.setCharacterEncoding("utf-8");
response.setContentType("application/json;charset=utf-8");
String flag = "0"; HSSFWorkbook workbook = new HSSFWorkbook();//创建对象
int rowNum=1;
HSSFSheet sheet = workbook.createSheet("电量表"); //在Excel中建一个工作表,其名为默认值
String[] name={"时间","ID","负载电量","风能电量","光伏电量","电池电量"};//字段名,就是excel中的标题头
List<String> list1 = null;
Map<String,List> map = new HashMap<String, List>();    
for (int i = 0; i < list.size(); i++) {
list1 = new ArrayList<String>();
list1.add(list.get(i).getTime());
list1.add(list.get(i).getID());
list1.add(list.get(i).getLoad_PH());
list1.add(list.get(i).getWind_PH());
list1.add(list.get(i).getSun_PH());
list1.add(list.get(i).getBattery_PH());
map.put(i+"", list1);
}
int columnCount = name.length;
HSSFRow row1 = sheet.createRow(0); //在索引0的位置创建行
for (short i = 0; i <columnCount; i++) { //遍历字段名
sheet.autoSizeColumn(i);
String columnName=name[i];
HSSFCell cell1 = row1.createCell(i);
cell1.setCellValue(columnName);
}
if(columnCount>=1){
for (int j = 0; j < map.size(); j++) {
HSSFRow row = sheet.createRow(j+1);
list1 = map.get(j+"");
for (short i = 0; i <columnCount; i++) { //遍历集合
HSSFCell cell = row.createCell(i); //将遍历到的写到单元格
sheet.autoSizeColumn(i);
cell.setCellValue(list1.get(i));
}
}
} ByteArrayOutputStream os = new ByteArrayOutputStream();
workbook.write(os);
byte[] content = os.toByteArray();
InputStream is = new ByteArrayInputStream(content);
// 设置response参数,可以打开下载页面
response.reset();
response.setContentType("application/vnd.ms-excel;charset=utf-8");
response.setHeader("Content-Disposition", "attachment;filename="+ new String(("电量表.xls").getBytes(), "iso-8859-1"));  //excel的表格名称
ServletOutputStream out = response.getOutputStream();
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(is);
bos = new BufferedOutputStream(out);
byte[] buff = new byte[2048];
int bytesRead;
// Simple read/write loop.
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
} catch (final IOException e) {
throw e;
} finally {
if (bis != null)
bis.close();
if (bos != null)
bos.close();
}
return null;
}

bizImpl层

    //查找电量中的信息
@Override
public List<TableEle> queEle(TableEle tableEle) {
return eleMapper.queEle(tableEle);
}