1. 程式人生 > >java 讀取資料庫資料並下載為Excel

java 讀取資料庫資料並下載為Excel

java 讀取資料庫資料並下載為Excel

前臺

html

<input type="button" id="javaExcel" value="java下載表格">

script

<script>
    $("#javaExcel").click(function () {
        $.ajax({
            type: "POST",
            url: "../java/excel",
            data:{name:"javaExcel"},
            dataType: "json"
, success: function (data) { alert(data.status); }, error:function () { alert("錯誤") } }); })
</script>

controller

private Map excel(){
        Map map =new HashMap();
        map.put("status","false"
); try { log.info("recent inactive hospital statistics start"); //命名行名 List<String> cellNameList = new ArrayList<>(); cellNameList.add("醫院id"); cellNameList.add("醫院名稱"); cellNameList.add("渠道號"); cellNameList.add
("聯絡人"); cellNameList.add("總關注數"); cellNameList.add("不活躍天數"); cellNameList.add("最後活躍日期"); cellNameList.add("申請日期"); cellNameList.add("建立天數"); //給檔案命名及設定路徑,如果該路徑下有該檔案則覆蓋該檔案 String excelPath="/Users/user/Desktop/不活潑醫院資訊.xls"; //給表命名 String title=LocalDate.now().minusDays(14)+"至"+LocalDate.now().minusDays(8)+"不活潑醫院資訊"; HSSFWorkbook excel = Excel.createExcel(title, cellNameList); //寫資料,這裡隨便寫點資料(可以從資料庫讀資料然後迴圈寫) for(int i=1;i<5;i++){ List<String> excelData = new ArrayList<>(); excelData.add(i+""); excelData.add("name"); excelData.add(i+""); excelData.add("聯絡人"); excelData.add("總關注數"); excelData.add("不活躍天數"); excelData.add("最後活躍日期"); excelData.add("申請日期"); excelData.add("建立天數"); excel = Excel.createExcelData(excel, excelData, i); } //輸出資料 FileOutputStream fos = new FileOutputStream(excelPath); excel.write(fos); fos.close(); map.put("status","true"); } catch (Exception e) { e.printStackTrace(); } return map; }

util包的工具類

public class Excel {

    public static HSSFWorkbook createExcel(String sheetName, List<String> cellNameList) {

        HSSFWorkbook excel = new HSSFWorkbook();
        HSSFSheet sheet = excel.createSheet(sheetName);
        HSSFRow row = sheet.createRow(0);
        int cellIndex = 0;
        for (String cellName : cellNameList) {
            HSSFCell cell = row.createCell(cellIndex);
            cell.setCellValue(cellName);
            cellIndex++;
        }
        return excel;
    }

    public static HSSFWorkbook createExcelData(HSSFWorkbook excel, List<String> excelData,int rowIndex){
        HSSFRow row=excel.getSheetAt(0).createRow(rowIndex);
        for(int i = 0; i < excelData.size(); i++){
            row.createCell(i).setCellValue(excelData.get(i));
        }
        return excel;
    }


}