Chinaunix首页 | 论坛 | 博客
  • 博客访问: 7068285
  • 博文数量: 702
  • 博客积分: 10821
  • 博客等级: 上将
  • 技术积分: 12031
  • 用 户 组: 普通用户
  • 注册时间: 2005-12-02 10:41
个人简介

中科院云平台架构师,专注于数字化、智能化,技术方向:云、Linux内核、AI、MES/ERP/CRM/OA、物联网、传感器、大数据、ML、微服务。

文章分类

全部博文(702)

分类:

2006-03-16 10:38:42


作者:李书鹏 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;
}
}

调用方法:


导出文件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


相关文章
阅读(1980) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~