仓酷云

 找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 1098|回复: 19
打印 上一主题 下一主题

[学习教程] JAVA编程:一个用servlet完成导出csv文件的实例

[复制链接]
分手快乐 该用户已被删除
跳转到指定楼层
楼主
发表于 2015-1-18 11:34:06 | 显示全部楼层 回帖奖励 |倒序浏览 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有帐号?立即注册

x
你对java乐观有点盲目。java的关键就是在服务器上表现优异,而且它提供了整个开发所需要的工具。应该是说,看哪天。net有没有机会赶上java。servlet李书鹏tukeyli@sohu.com

关头字:JavaServletCSV

本文完成了一个基于servlet手艺的复杂的csv文件导出的程序实例。

代码以下,个中setCsvData函数的感化是设置导出的数据,并将了局保留于Vector中,实践使用时能够恣意扩大该函数:

packagecommon;

importjava.io.IOException;
importjava.io.PrintWriter;
importjava.util.Vector;
importjavax.servlet.ServletException;
importjavax.servlet.http.*;

publicclassGo2CsvextendsHttpServlet
{
publicVectorvecCsvData;

privateStringFileName;

publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)
//throwsServletException,IOException
{
FileName="Untitled.csv";//defaultfilename

vecCsvData=newVector();

//setsthedatatobeexported
setCsvData(request);

//Exportingvectortocsvfile
StringstrOut="";
for(inti=0;i<vecCsvData.size();i++)
{
String[]strLine=(String[])vecCsvData.elementAt(i);
intcol_num=strLine.length;
for(intj=0;j<col_num;j++)
{
strOut+=strLine[j];
if(j<col_num-1)
{
strOut+=",";
}
}
strOut+="
";
}

//*****OutputstrOuttoResponse******
response.reset();//Resettheresponse
response.setContentType("application/octet-stream;charset=GB2312");//theencodingofthisexampleisGB2312
response.setHeader("Content-Disposition","attachment;filename=""+FileName+""");

PrintWriterout;
try
{
out=response.getWriter();
out.write(strOut);
}
catch(IOExceptione)
{
e.printStackTrace();
}
//***************************************
}

publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException
{
doGet(request,response);
}

/**
*Setsthedatatobeexported
*@paramrequest
*/
publicvoidsetCsvData(HttpServletRequestrequest)
{
//Writingvector
for(inti=0;i<5;i++)
{
String[]strLine=newString[10];
for(intj=0;j<10;j++)
{
strLine[j]=Integer.toString(i)+"-"+Integer.toString(j);
}
vecCsvData.addElement(strLine);
}
}

/**
*Setsthefilenametobeexported
*@paramfilename
*/
publicvoidsetFileName(Stringfilename)
{
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

还得说上一点,就java本质而言,是面相对象的,但是你有没有发现,java也不全是,比如说基本类型,int,那他就是整型而不是对象,转换类型是还得借助包装类。
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|Archiver|手机版|仓酷云 鄂ICP备14007578号-2

GMT+8, 2024-5-24 01:40

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表