2015-04-04 39 views
0

我想將查詢結果導出爲ex​​cel或csv文件。 我正在使用hibernate struts。 是否有任何查詢可以直接將excel導出到指定的位置? 在MySQL數據庫中,'進入outfile'查詢工作正常,但在休眠狀態它不起作用。 我嘗試使用本機的SQL,但它給出的錯誤'無法執行批量操作查詢',無論如何我無法解決這個問題。 我正在使用MySQL數據庫。休眠導出爲csv

回答

2

如果你正在編寫一個Web應用程序,並使用Spring,你可以通過將數據寫入到輸出流做

寫一個簡單的類來構建你的迴應

public class CsvResponse {  
    private final String filename; 
    private final List<YourPojo> records; 

    public CsvResponse(List<YourPojo> records, String filename) { 
     this.records = records; 
     this.filename = filename; 
    } 
    public String getFilename() { 
     return filename; 
    } 
    public List<YourPojo> getRecords() { 
     return records; 
    } 
} 

現在寫一個消息轉換器它們寫入到輸出流

public class CsvMessageConverter extends AbstractHttpMessageConverter<CsvResponse> { 
    public static final MediaType MEDIA_TYPE = new MediaType("text", "csv", Charset.forName("UTF-8")); 
    public CsvMessageConverter() { 
     super(MEDIA_TYPE); 
    } 

    protected boolean supports(Class<?> clazz) { 
     return CsvResponse.class.equals(clazz); 
    } 

    protected void writeInternal(CsvResponse response, HttpOutputMessage output) throws Exception { 
     output.getHeaders().setContentType(MEDIA_TYPE); 
     output.getHeaders().set("Content-Disposition", "attachment; filename=\"" + response.getFilename() + "\""); 
     OutputStream out = output.getBody(); 

     CsvWriter writer = new CsvWriter(new OutputStreamWriter(out), '\u0009'); 
     List<YourPojo> allRecords = response.getRecords(); 
     for (int i = 1; i < allRecords.size(); i++) { 
      YourPojo aReq = allRecords.get(i); 
      writer.write(aReq.toString()); 
     } 
     writer.close(); 
    } 
} 

此信息轉換器添加到您的應用程序上下文配置文件

<mvc:annotation-driven> 
    <mvc:message-converters register-defaults="true"> 
     <bean class="com.yourpackage.CsvMessageConverter"/> 
    </mvc:message-converters> 
</mvc:annotation-driven> 

最後控制器將看起來像

@RequestMapping(value = "/csvData", method = RequestMethod.GET, produces="text/csv") 
@ResponseBody 
public CsvResponse getFullData(HttpSession session) throws IOException { 
     // get data 
     List<YourPojo> allRecords = yourService.getData(); 

     return new CsvResponse(allRecords, "yourData.csv"); 
} 

我發現使用JAX RS here類似的方式。

但底線是你將不得不使用一個REST機制獲取數據到輸出流,如果你想這樣做的正確的方式,但如果你唯一的目標是將數據放入一個文件你可以把你的數據放在一個列表中,然後簡單地寫入一個文件。

+0

謝謝。我正在使用struts2,並由FileWriter完成。我將Query結果集存儲到List(Casted to MyPojo)中,並使用for循環將數據寫入文件,並用逗號分隔。 – user1724662 2015-04-06 04:24:21