一個用servlet實現匯出csv檔案的執行個體

來源:互聯網
上載者:User
servlet 作者:李書鵬 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 < vecCsvData.size(); i++)
{
String[] strLine = (String[])vecCsvData.elementAt(i);
int col_num = strLine.length;
for (int j = 0; j < col_num; j++)
{
strOut += strLine[j];
if (j < col_num - 1)
{
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 < 5; i++)
{
String[] strLine = new String[10];
for (int j = 0; j < 10; 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


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.