本文实现了一个基于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

阅读更多
个人分类: java
想对作者说点什么? 我来说一句

Servlet和JSP实现的博客小程序

2017年01月22日 3.91MB 下载

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭