开发工具:eclipse+apache2.2+Tomcat6.0
开发环境:webwork+spring+iBatis
TestBO.java
/**
* CSVダウンロード
*
* @param inputParam 画面検索入力条件
* @return InputStream
* @throws IOException
*/
public InputStream downloadCSV(String inputParam) throws IOException {
//将数据以list<bean>的方式从DB中取出
List<OutputVO> outputList = TestDAO.selectAllTestData(inputParam);
FileOutputStream fos = null;
try {
File temFile = File.createTempFile("tmp", ".csv");
temFile.deleteOnExit();
fos = new FileOutputStream(temFile);
OutputStreamWriter osw = new OutputStreamWriter(fos, "MS932");
BufferedWriter bw = new BufferedWriter(osw);
StringBuilder sb = null;
if (null != outputList) {
sb = new StringBuilder();
sb.append("項目1,");
sb.append("項目2,");
sb.append("項目3,");
sb.append("項目4,");
...
sb.append("項目n");
String header = sb.toString();
bw.write(header);
bw.newLine();
for (OutputVO vo : outputList) {
sb = new StringBuilder();
sb.append(vo.getXXX() + ",");
sb.append(vo.getYYY() + ",");
sb.append(vo.getZZZ() + ",");
...
sb.append(vo.getWWW());
bw.write(sb.toString());
bw.newLine();
}
bw.flush();
bw.close();
osw.close();
fos.close();
return new FileInputStream(temFile);
} catch (IOException e) {
return null;
} finally {
try {
if(output != null)
output.close();
} catch(IOException ioe) { }
}
}
TestAction.java
private TestBO testBO;
private InputStream inputStream;
/**
* CSVファイルダウンロード
* @param
* @return String
*/
public String downloadCSV() throws Exception {
try {
inputStream = testBO.downloadCSV(inputParam);
} catch (Exception e) {
log.error(e, e);
throw e;
}
return SUCCESS;
}
xwork.xml
<action name="downloadCSV" class="jp.zhuzhu.TestAction" method="downloadCSV">
<result name="success" type="stream">
<param name="inputName">inputStream</param>
<param name="contentType">application/x-msdownload; charset=Windows31J</param>
<param name="contentDisposition">attachment; filename="test.csv"</param>
<param name="bufferSize">1024</param>
</result>
</action>
test.jsp
<script type="text/javascript">
function download(){
document.searchForm.target = "downloadFrm";
document.searchForm.action = "downloadCSV.action";
document.searchForm.submit();
}
</script>
<form method="get" name="searchForm" action="">
<div class="download"><input type="button" value="Download" οnclick="javawscript:download()"/></div>
</form>
<iframe id="downloadFrm" name="downloadFrm" style="display:none" scrolling="no" frameborder="0"></iframe>
如果数据自身有逗号,显示在csv里会出现自动分割的现象。
解决办法是在该列里加上引号。
sb.append("\"" + vo.getSupportNote() + "\"");