1.导出csv文件
后台导出:CSVUtils工具类:
/*** * CSV文件导出工具类* * @author* @reviewer*/ public class CSVUtils {public static File createCSVFile(List<Object> head, List<List<Object>>dataList, String outPutPath, String filename) {File csvFile = null; BufferedWriter csvWtriter = null;
try {
csvFile =new File(outPutPath + File.separator + filename + ".csv"); File parent =csvFile.getParentFile();
if (parent != null && !parent.exists()) {parent.mkdirs(); } csvFile.createNewFile();// GB2312使正确读取分隔符","
csvWtriter = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(csvFile), "GB2312"), 1024); //写入文件头部
writeRow(head, csvWtriter);// 写入文件内容
for (List<Object> row : dataList) {
writeRow(row, csvWtriter);}
csvWtriter.flush(); }
catch (Exception e) { e.printStackTrace(); }finally { try { csvWtriter.close(); } catch (IOException e) {e.printStackTrace(); } } return csvFile; }/*** 写一行数据方法* * @param row* @param csvWriter* @throws IOException*/private static void writeRow(List<Object> row, BufferedWriter csvWriter)throws IOException { // 写入文件头部
for (Object data : row) {
StringBuffer sb = new StringBuffer();
String rowStr = sb.append("\"").append(data).append("\",") .toString();csvWriter.write(rowStr); } csvWriter.newLine(); }}
>>>网页导出:
(1),先在后台将要导出的信息拼接成 “属性值”,“属性值”,“属性值”,\n“属性值”,。。\n。的形式,
(2),向网页传值,
(3),引入FileSaver.js,
function exportCsv2(dataStr, fileName) {//Excel打开后中文乱码添加如下字符串解决var exportContent = "\uFEFF";var blob = new Blob([ exportContent + dataStr ], {type : "text/plain;charset=utf-8"});saveAs(blob, fileName + ".csv");//导出文件格式自定义。}
调用:
var dataStr = '<s:property value="dataStr" />';
var filename = '<s:property value="filename" />';
$("#btn_export_refund").click(function() {
exportCsv2(dataStr,filename);
});