java web导出csv_JavaWeb导出CSV文件

Controller层 :

@RequestMapping(value = "/exportCsv")

public Result exportCsv(Timestamp startTime, Timestamp endTime) throws ParseException {

Integer pageNo = 1;

String st = DateUtil.dateToStr(startTime, "yyyyMMddHHmmss");

String et = DateUtil.dateToStr(endTime, "yyyyMMddHHmmss");

List listcw = new ArrayList();

List listUserMoney = new ArrayList();

Integer perPageNum = 100000000;

listUserMoney = businessService.getTGBexpend4(startTime, endTime, pageNo, perPageNum);

double trueMoney = 0.0;

int userID = 0;

WuCsvVO gftj = new WuCsvVO();

WuCsvVO gf = null;

for (int i = 0; i < listUserMoney.size(); i++) {

UserMoney money = listUserMoney.get(i);

if (userID != money.getUserID()) {

userID = money.getUserID();

gf = new WuCsvVO();

trueMoney = 0.0;

listcw.add(gf);

}

if (money.getMoneyType().equals("S")) {//

gf.setTopicMoney(money.getMoneyNum());

trueMoney = Arith.add(trueMoney, money.getMoneyNum());

gftj.setTopicMoney(Arith.add(gftj.getTopicMoney(), money.getMoneyNum()));

} else if (money.getMoneyType().equals("M") || money.getMoneyType().equals("N")) { //

gf.setMatchMoney(money.getMoneyNum());

trueMoney = Arith.add(trueMoney, money.getMoneyNum());

gftj.setMatchMoney(Arith.add(gftj.getMatchMoney(), money.getMoneyNum()));

} else if (money.getMoneyType().equals("W")) {

gf.setShuoMoney(money.getMoneyNum());

trueMoney = Arith.add(trueMoney, money.getMoneyNum());

gftj.setShuoMoney(Arith.add(gftj.getShuoMoney(), money.getMoneyNum()));

} else if (money.getMoneyType().equals("C")) {

gf.setPcMoney(money.getMoneyNum());

trueMoney = Arith.add(trueMoney, money.getMoneyNum());

gftj.setPcMoney(Arith.add(gftj.getPcMoney(), money.getMoneyNum()));

} else if (money.getMoneyType().equals("SLT")) {

gf.setSpmatchMoney(money.getMoneyNum());

trueMoney = Arith.add(trueMoney, money.getMoneyNum());

gftj.setSpmatchMoney(Arith.add(gftj.getSpmatchMoney(), money.getMoneyNum()));

} else if (money.getMoneyType().equals("F")) {

continue;

}

gf.setUserID(money.getUserID());

gf.setUserName(money.getUserName());

gf.setTrueMoney(trueMoney);

gftj.setTrueMoney(Arith.add(gftj.getTrueMoney(), money.getMoneyNum()));

}

gftj.setUserName("小计:");

listcw.add(gftj);

String realPath = request.getRealPath("/WEB-INF/export"); // 获取绝对路径

String path = realPath.replace("\\", "/");

String fileName = st + "_" + et + "_"; // 定义文件名称

List> exportData = new ArrayList>();

Map row = new LinkedHashMap();

LinkedHashMap map = new LinkedHashMap();

map.put("1", "栏目1");

map.put("2", "栏目2");

map.put("3", "栏目3");

map.put("4", "栏目4");

map.put("5", "栏目5");

for (WuCsvVO data : listcw) { // 执行导出操作

row = new LinkedHashMap();

row.put("1", data.getUserName());

row.put("2", data.getTopicMoney());

row.put("3", data.getShuoMoney());

row.put("4", data.getPcMoney());

row.put("5", data.getMatchMoney());

exportData.add(row);

}

File file = CsvUtil.createCSVFile(exportData, map, realPath, fileName);

String fileName2 = file.getName();

CsvUtil.download(path + "/" + fileName2, response);

return new Result(true);

}

工具类:

public class CsvUtil {

private static final org.apache.commons.logging.Log LOG = LogFactory.getLog(CsvUtil.class);

/**

* 生成为CVS文件

*

* [[@param](https://my.oschina.net/u/2303379)] exportData

* 源数据List

* [[@param](https://my.oschina.net/u/2303379)] map

* csv文件的列表头map

* [[@param](https://my.oschina.net/u/2303379)] outPutPath

* 文件路径

* [[@param](https://my.oschina.net/u/2303379)] fileName

* 文件名称

* @return

*/

@SuppressWarnings("rawtypes")

public static File createCSVFile(List exportData, LinkedHashMap map, String outPutPath, String fileName) {

File csvFile = null;

BufferedWriter csvFileOutputStream = null;

try {

File file = new File(outPutPath);

if (!file.exists()) {

file.mkdir();

}

// 定义文件名格式并创建

csvFile = File.createTempFile(fileName, ".csv", new File(outPutPath));

// UTF-8使正确读取分隔符","

csvFileOutputStream = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(csvFile), "UTF-8"),

1024);

// 写入文件头部

for (Iterator propertyIterator = map.entrySet().iterator(); propertyIterator.hasNext();) {

java.util.Map.Entry propertyEntry = (java.util.Map.Entry) propertyIterator.next();

csvFileOutputStream.write(

"" + (String) propertyEntry.getValue() != null ? (String) propertyEntry.getValue() : "" + "");

if (propertyIterator.hasNext()) {

csvFileOutputStream.write(",");

}

}

csvFileOutputStream.newLine();

// 写入文件内容

for (Iterator iterator = exportData.iterator(); iterator.hasNext();) {

Object row = (Object) iterator.next();

for (Iterator propertyIterator = map.entrySet().iterator(); propertyIterator.hasNext();) {

java.util.Map.Entry propertyEntry = (java.util.Map.Entry) propertyIterator.next();

csvFileOutputStream.write((String) BeanUtils.getProperty(row, (String) propertyEntry.getKey()));

if (propertyIterator.hasNext()) {

csvFileOutputStream.write(",");

}

}

if (iterator.hasNext()) {

csvFileOutputStream.newLine();

}

}

csvFileOutputStream.flush();

} catch (Exception e) {

e.printStackTrace();

} finally {

try {

csvFileOutputStream.close();

} catch (IOException e) {

e.printStackTrace();

}

}

return csvFile;

}

/**

* 下载csv文件

*

* @param path

* @param response

*/

public static void download(String path, HttpServletResponse response) {

try {

// path是指下载的文件的路径。

File file = new File(path);

// 取得文件名。

String filename = file.getName();

filename=filename.substring(0,29)+".csv";

// 以流的形式下载文件。

InputStream fis = new BufferedInputStream(new FileInputStream(path));

byte[] buffer = new byte[fis.available()];

fis.read(buffer);

fis.close();

// 清空response

response.reset();

// 设置response的Header

response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));

response.addHeader("Content-Length", "" + file.length());

OutputStream toClient = new BufferedOutputStream(response.getOutputStream());

response.setContentType("application/vnd.ms-excel;charset=UTF-8");

toClient.write(buffer);

//处理乱码

toClient.write(new byte []{( byte ) 0xEF ,( byte ) 0xBB ,( byte ) 0xBF });

toClient.flush();

toClient.close();

} catch (IOException ex) {

ex.printStackTrace();

}

}

页面请求:

$(".gaofeicsv").click(function(){

var startTime=$("#startTime").val();

var endTime=$("#endTime").val();

window.location.href ="/new/manage/gaofei/exportCsv?startTime="+startTime + "&endTime=" + endTime;

});

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值