作者:李书鹏 tukeyli@sohu.com
关键字: Java Servlet CSV
本文实现了一个基于servlet技术的简单的csv文件导出的程序实例。
代码如下,其中setCsvData函数的作用是设置导出的数据,并将结果保存于Vector中,实际应用时可以任意扩展该函数:
package common;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Vector;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class Go2Csv extends HttpServlet
{
public Vector vecCsvData;
private String FileName;
public void doGet(HttpServletRequest request, HttpServletResponse response)
//throws ServletException, IOException
{
FileName = "Untitled.csv";//default file name
vecCsvData = new Vector();
//sets the data to be exported
setCsvData(request);
//Exporting vector to csv file
String strOut = "";
for (int i = 0; i
{
String[] strLine = (String[])vecCsvData.elementAt(i);
int col_num = strLine.length;
for (int j = 0; j
{
strOut += strLine[j];
if (j
{
strOut += ",";
}
}
strOut += "\n";
}
//***** Output strOut to Response ******
response.reset();// Reset the response
response.setContentType("application/octet-stream;charset=GB2312");// the encoding of this example is GB2312
response.setHeader("Content-Disposition","attachment; filename=\"" + FileName + "\"");
PrintWriter out;
try
{
out = response.getWriter();
out.write(strOut);
}
catch (IOException e)
{
e.printStackTrace();
}
//***************************************
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
doGet(request, response);
}
/**
* Sets the data to be exported
* @param request
*/
public void setCsvData(HttpServletRequest request)
{
//Writing vector
for (int i = 0; i
{
String[] strLine = new String[10];
for (int j = 0; j
{
strLine[j] = Integer.toString(i) + "-" + Integer.toString(j);
}
vecCsvData.addElement(strLine);
}
}
/**
* Sets the file name to be exported
* @param filename
*/
public void setFileName(String filename)
{
FileName = filename;
}
}
调用方法:
http://hostname:port/ApplicationName/servlet/common.Go2Csv
导出文件Untitled.csv内容如下:
0-0,0-1,0-2,0-3,0-4,0-5,0-6,0-7,0-8,0-9
1-0,1-1,1-2,1-3,1-4,1-5,1-6,1-7,1-8,1-9
2-0,2-1,2-2,2-3,2-4,2-5,2-6,2-7,2-8,2-9
3-0,3-1,3-2,3-3,3-4,3-5,3-6,3-7,3-8,3-9
4-0,4-1,4-2,4-3,4-4,4-5,4-6,4-7,4-8,4-9