文件的io流一直是我学习java中比较避讳的。不知道为什么?可能是那些管子套管子的操作比较不容易理解吧。但是不学不证明不用啊。如今把点滴经验代码贴出来供大家参考。闲话少序,看代码:
由于导出excle肯定应该是一个列表的操作。所以要建一个普通的bean对象。本文假设该bean叫CouLog.java。
1 页面按钮<input type="button" οnclick="excel()" value="导出Excel" />----jsp页面的html.自然不必多说
2 对应的js脚本。-----这个也不必了吧。都是基础
function excel(){
document.sendform.action="ClientAction.do?method=ExcelAction";
document.forms[0].submit();
}
3 具体上面的action的类我就不写了。因为没有什么必要。这就是根据某些条件查出的一个list然后存到了request里面。
4 struts返回的页面
<%@page contentType="text/html;charset=GBK"%>
<%@page import="java.io.*"%>
<%@page import="java.util.*"%>
<%@page import="com.guodu.util.CSVWriter"%>-------->上面显示的csv工具类
<%@page import="com.guodu.dataservice.datamodel.CouLog"%>------->自定义的一个普通的类,用于页面list的取出
<%
response.reset();
response.setContentType("application/OCTET-STREAM;charset=gb2312");
response.setHeader("pragma", "no-cache");
response.addHeader("Content-Disposition", "attachment;filename=/"my.csv/"");//点击导出excle按钮时候页面显示的默认名称
CSVWriter csv = new CSVWriter(response.getWriter(), 1, ',', '/"', true);
csv.put("发送时间");
csv.put("接收者");
csv.put(" 接收者号码");
csv.put("内容");
csv.put("接收时间");
csv.put("状态");----这些put的对象就是excle文件的现实的行标题。
csv.nl();
List infoList = (ArrayList) request.getAttribute("sendclientlist"); //取出在action里面存的list。
if (infoList != null) {
int count = 0;
for (Iterator it = infoList.iterator(); it.hasNext(); ) {
CouLog coulog =(CouLog)it.next();//一个普通的bean
csv.put(coulog.getSendtime());// 发送时间
csv.put(coulog.getInceptname());//接收者
csv.put(coulog.getInceptphone());//接收者号码
csv.put(coulog.getInceptpcontent());//内容
csv.put(coulog.getInceptptime());//接收的时间
csv.put(coulog.getState()); //状态
csv.nl();//换行
if(count++ >= 10000){
break;
}
}
}
csv.close();
%>
5 CSVWriter.java------CSVWriter工具包,负责处理excle的流操作,具体细节小弟也没有研究过.
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
/**
* Write CSV (Comma Separated Value)
* files.
*
* This format is used my Microsoft Word and Excel.
* Fields are separated by commas, and enclosed in
* quotes if they contain commas or quotes.
* Embedded quotes are doubled.
* Embedded spaces do not normally require surrounding quotes.
* The last field on the line is not followed by a comma.
* Null fields are represented by two commas in a row.
*
* @author copyright (c) 2002-2004 Roedy Green Canadian Mind Products
* @version 1.0 2002 March 27
* 1.1 2002 March 28
* - allow variable separator
* - add close method
* 1.2 2002 April 23
* - put in to separate package
* 1.3 2002 April 24
* - three levels of quoting
* 1.4 2002 April 24
* - convenience constructor
* - put(null) now means nl.
* 1.6 2002 May 25
* - allow choice of quote char
* 1.9 2002 November 14
* - trim parameter to control whether
* fields are trimmed of
* lead/trail whitespace (blanks, Cr, Lf, Tab etc.)
* before writing.
*/
public class CSVWriter
{
static final boolean DEBUGGING = false;
/**
* Constructor
*
* @param pw Writer where fields will be written.
* @param quoteLevel
* 0 = minimal quotes
* 1 = quotes also around fields containing spaces
* 2 = quotels around all fields.
* whether or not they contain commas, quotes or spaces.
* @param separator
* field separator character, usually ',' in North America,
* ';' in Europe and sometimes '/t' for tab.
* @param quote
* char to use to enclose fields containing a separator,
* usually '/"'
*
* @param trim true if writer should trim leading/trailing whitespace
* (e.g. blank, cr, Lf, tab) before writing
* the field.
*/
public CSVWriter ( Writer pw, int quoteLevel, char separator, char quote, boolean trim)
{
if ( pw instanceof PrintWriter )
{
this.pw = (PrintWriter) pw;
}
else
{
this.pw = new PrintWriter(pw);
}
if ( this.pw == null )
{
throw new IllegalArgumentException("invalid Writer");
}
this.quoteLevel = quoteLevel;
this.separator = separator;
this.quote = quote;
this.trim = trim;
}
/**
* convenience Constructor, defaults to quotelevel 1, comma separator , trim
*
* @param pw Writer where fields will be written.
*
*/
public CSVWriter ( Writer pw)
{
this(pw, 1, ',', '/"', true);
}
/**
* PrintWriter where CSV fields will be written.
*/
PrintWriter pw;
/**
* how much extra quoting you want
*/
int quoteLevel;
/**
* field separator character, usually ',' in North America,
* ';' in Europe and sometimes '/t' for tab.
*/
char separator;
/**
* quote character, usually '/"'
* '/'' for SOL used to enclose fields containing a separator character.
*/
private char quote;
/**
* true if write should trim lead/trail whitespace
* from fields before writing them.
*/
private final boolean trim;
/**
* true if there has was a field previously written to
* this line, meaning there is a comma pending to
* be written.
*/
boolean wasPreviousField = false;
/**
* Write one csv field to the file, followed by a separator
* unless it is the last field on the line. Lead and trailing blanks will be removed.
*
* @param s The string to write. Any additional quotes or
* embedded quotes will be provided by put.
* Null means start a new line.
*/
public void put(String s)
{
if ( pw == null )
{
throw new IllegalArgumentException("attempt to use a closed CSVWriter");
}
if ( s == null )
{
//nl();zhanghongwei modify
s = "";
//return;
}
if ( wasPreviousField )
{
pw.print(separator);
}
if ( trim )
{
s = s.trim();
}
if ( s.indexOf(quote) >= 0 )
{
/* worst case, needs surrounding quotes and internal quotes doubled */
pw.print (quote);
for ( int i=0; i<s.length(); i++ )
{
char c = s.charAt(i);
if ( c == quote )
{
pw.print(quote);
pw.print(quote);
}
else
{
pw.print(c);
}
}
pw.print (quote);
}
//else if ( quoteLevel == 2 || quoteLevel == 1 && s.indexOf(' ') >= 0 || s.indexOf(separator) >= 0 )
else if ( quoteLevel == 2 || s.indexOf(separator) >= 0 )//空格不加双引号
{
/* need surrounding quotes */
pw.print (quote);
pw.print(s);
pw.print (quote);
}
else
{
/* ordinary case, no surrounding quotes needed */
pw.print(s);
}
/* make a note to print trailing comma later */
wasPreviousField = true;
}
/**
* Write a new line in the CVS output file to demark the end of record.
*/
public void nl()
{
if ( pw == null )
{
throw new IllegalArgumentException("attempt to use a closed CSVSWriter");
}
/* don't bother to write last pending comma on the line */
pw.print("/r/n"); /* windows conventions since this is a windows format file */
wasPreviousField = false;
}
/**
* Close the PrintWriter.
*/
public void close()
{
if ( pw != null )
{
pw.close();
pw = null;
}
}
/**
* Test driver
*
* @param args not used
*/
public static void main(String[] args)
{
//if ( DEBUGGING )
// {
try
{
// write out a test file
CSVWriter csv = new CSVWriter(new FileWriter("d://temp.csv"), 1, ',', '/"', false);
csv.nl();
csv.nl();
csv.put("abcssgggggggggggkkkkssssssssssss");
csv.put("def");
csv.put("g h i");
csv.put("jk,l");
csv.put("m/"n/'o ");
csv.nl();
csv.put("m/"n/'o ");
csv.put(" ");
csv.put("a");
csv.put("x,y,z");
csv.put("x;y;z");
csv.nl();
csv.close();
}
catch ( IOException e )
{
e.printStackTrace();
System.out.println(e.getMessage());
}
// } // end if
} // end main
} // end CSVWriter class.