import au.com.bytecode.opencsv.CSVWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URLEncoder;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
public class ExportExcel {
String[] options;
List list;
OutputStream os;
CSVWriter writer;
public ExportExcel(String[] options, List list, HttpServletResponse response) {
this.options = options;
this.list = list;
String filename = "导出.csv";
String encodeString = null;
try {
encodeString = URLEncoder.encode(filename, "utf-8");
response.setHeader("Content-disposition", "attachment;filename=" + encodeString);
this.os = response.getOutputStream();
this.writer = new CSVWriter(new OutputStreamWriter(os));
} catch (Exception e) {
e.printStackTrace();
}
}
public void export() {
int row = list.size();
int cloumn = options.length;
//写入列名称
writer.writeNext(options);
for (int i = 0; i < row; i++) {
Object[] obj = (Object[]) list.get(i);
String str[] = new String[cloumn];
for (int j = 0; j < cloumn; j++) {
if(j == 1 || j == 3){
str[j] = obj[j] == null ? "" : "/t"+obj[j].toString(); //导出CSV文件时第一列跟第三列加/t,其余不加,使用时注意导出文件中一列与三列的值
}else
str[j] = obj[j] == null ? "" : obj[j].toString();
}
writer.writeNext(str);
}
try {
writer.close();
os.flush();
os.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
// 方法的調用 ExportExcel exportExcel = new ExportExcel(obj, list,response);
// exportExcel.Export();
22万+

被折叠的 条评论
为什么被折叠?



