1. 程式人生 > >java匯入Excel表格

java匯入Excel表格

像我們日常開發中,我們常常有查詢到一些我們需要的列印的資料的話,我們往往先要匯入excel表格或者Words文件。

方便我們來匯入電腦然後進行列印。我這邊以匯入Excel表格為例。

pom.xml的配置相關依賴

<!--匯入excel表格所依賴的jar-->
<dependencies>
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi</artifactId>
        <version>3.9</version>
    </dependency>

    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>3.9</version>
    </dependency>

-----------------------------------------------------------------------------

Controller相關的控制層的程式碼

/*
*將客房資訊匯入excel表格
* */
@RequestMapping(value = "/roomExcelDownloads",method = RequestMethod.GET)
public void downloadAllClassmate(HttpServletResponse response)throws IOException{
    HSSFWorkbook workbook=new HSSFWorkbook();
    HSSFSheet sheet=workbook.createSheet("客房資訊表");
    List<HotelRoom> classmateList=hotelRoomService.findAll();
    String fileName="hotelRoom"+".xls";//設定匯出的檔名字
    int rowNum=1;
    String [] headers={"房間編號","房間名稱","層數","房間型別","相關資訊"};
    //headers表示excel表中第一行的表頭
    HSSFRow row=sheet.createRow(0);
    //excel表中新增表頭
    for(int i=0;i<headers.length;i++){
        HSSFCell cell=row.createCell(i);
        HSSFRichTextString text=new HSSFRichTextString(headers[i]);
        cell.setCellValue(text);
    }
    //在表中存放查詢的資料放入對應的列
    for(HotelRoom hotelRoom:classmateList){
        HSSFRow row1=sheet.createRow(rowNum);
        row1.createCell(0).setCellValue(hotelRoom.getRoomNumber());
        row1.createCell(1).setCellValue(hotelRoom.getRoomName());
        row1.createCell(2).setCellValue(hotelRoom.getLayer());
        row1.createCell(3).setCellValue(hotelRoom.getRoomType());
        row1.createCell(4).setCellValue(hotelRoom.getDescription());
        rowNum++;
    }
    response.setContentType("application/octet-stream");
    response.setHeader("Content-disposition","attachment;filename="+fileName);
    response.flushBuffer();
    workbook.write(response.getOutputStream());
}