之前的項目一直運行到tomcat7環境中,由於客戶要求使用webLogic服務器,項目部署到webLogic環境中,遇到很多問題,其中導出報表問題涉及範圍比較多,本人花了兩天時間一直研究,查資料,終於解決在webLogic環境下,導出excel表格問題。以下是關鍵性代碼:
// 設置response的Header
PrintWriter writer = null;
try
{
response.setContentType("octets/stream");
response.addHeader("Content-Disposition", "attachment;filename=" + new String(file.getName().getBytes("gbk"), "iso-8859-1"));
response.setContentLength(new Long(file.length()).intValue());
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
response.setCharacterEncoding("utf-8");
InputStream inputStream = null;
OutputStream os = null;
try
{
try
{
inputStream = new FileInputStream(file);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
writer = response.getWriter();
writer.write(JSON.toJSONString("下載文件出錯"));
writer.flush();
// throw new RoxException("下載文件出錯");
}
os = response.getOutputStream();
byte[] b = new byte[2048];
int length;
while ((length = inputStream.read(b)) > 0)
{
os.write(b, 0, length);
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
// throw new RoxException("下載文件出錯");
}
catch (IOException e)
{
e.printStackTrace();
// throw new RoxException("下載文件出錯");
}
finally
{
if (writer != null)
{
writer.close();
}
if (os != null)
{
try
{
os.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
if (inputStream != null)
{
try
{
inputStream.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
關鍵性代碼中,其中response.setContentLength(new Long(file.length()).intValue());代碼是關鍵代碼,如果不指定下載文件大小,在導出文件,使用excel2007打開,會提示“文件格式錯誤”,指定文件大小之後,在使用excel2007就可以正常打開了。