引入依赖:
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi --><dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>4.1.0</version></dependency>
@RequestMapping("/download")public void download(String year, String month, HttpServletResponse response,HttpServletRequest request) throws IOException {List<ProductList> productLists = loginService.findProdutSales(year, month);String filename = year + "年" + month + "月销售榜单";String sheetName = month + "月销售榜单";String titlename = year + "年" + month + "月销售榜单";String[] columnName = {"商品名称", "商品销量"};String[][] dataList = new String[productLists.size()][2]; //二维数字必须指定长度for (int i = 0; i < productLists.size(); i++) {dataList[i][0] = productLists.get(i).getName();dataList[i][1] = productLists.get(i).getSales();}//创建一个excel文件HSSFWorkbook excel =new HSSFWorkbook();//创建一个表HSSFSheet sheet = excel.createSheet(sheetName);//创建表的第一行HSSFRow row1=sheet.createRow(0);//创建第一行的第一个单元格HSSFCell cell=row1.createCell(0);//合并第一行的两个单元格 起始行 终止行 起始列 终止列sheet.addMergedRegion(new CellRangeAddress(0,0,0,1));//给第一行的的一个合并后的单元格赋值cell.setCellValue(titlename);//创建第二行HSSFRow row=sheet.createRow(1);for(int i=0;i<2;i++){row.createCell(i).setCellValue(columnName[i]);}//创建第三行 循环,都是数据for(int i=0;i<dataList.length;i++){ //二维数组的长度是行的长度,与列无关row=sheet.createRow(i+2);for(int j=0;j<2;j++){row.createCell(j).setCellValue(dataList[i][j]);}}