一个简单的导出csv文件的方法

本文介绍了一种从系统中导出电话记录为CSV文件的方法。主要包括三个步骤:首先,查询指定日期范围内的电话记录;其次,组织这些记录的数据为字符串格式,并确保每条记录之间用换行符隔开;最后,将整理好的字符串输出到CSV文件中并提供下载。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

分3步:
1, 查找对象列表
2, 组织字符串
3, 输出文件

代码片段:

//1, 查找对象列表
List callLogList = reportCallService.getCallLogList(fromDate, endDate);

//组织字符串,注意添加换行符
StringBuffer bf = new StringBuffer();

LocalCallLog cl = new LocalCallLog();
bf.append("Calllog ID").append(",").append("Src No").append(",")
.append("Dest No")
.append("\n");

for (Iterator it = callLogList.iterator(); it.hasNext();) {
cl = (LocalCallLog) it.next();
bf.append(cl.getCallLogId()).append(",").append(cl.getSrcNum())
.append(",").append(cl.getDestNum()).append("\n");
}
//输出文件
response.setContentType("application/x-download");

// String now = new SimpleDateFormat("h:mm a").format(new Date());
// now.replace(" ", "");
// String filenamedisplay = URLEncoder.encode("CallReport"+now
// +".csv","UTF-8");
String filenamedisplay = URLEncoder.encode("CallReport.csv", "UTF-8");
response.addHeader("Content-Disposition", "attachment;filename="
+ filenamedisplay);
PrintWriter pw = response.getWriter();
pw.write(bf.toString());

return null;
}
在Java中导出CSV文件一个常见的需求,尤其是在需要将数据保存到表格形式或与其他应用程序共享数据时。以下是几种常用的实现方法: ### 1. 使用 `BufferedWriter` 手动构建 CSV 文件 这是最基础的方式之一,直接通过字符串拼接的方式来创建CSV内容。 ```java import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; public class ExportCsv { public static void main(String[] args) { String filePath = "data.csv"; try (BufferedWriter bw = new BufferedWriter(new FileWriter(filePath))) { // 写入表头 bw.write("姓名,年龄,城市\n"); // 写入一行数据 bw.write("张三,25,北京\n"); bw.write("李四,30,上海\n"); } catch (IOException e) { System.out.println(e.getMessage()); } } } ``` 这种方法简单易懂,但需要注意转义特殊字符如逗号、换行符等,并且对于大量数据处理效率较低。 ### 2. 使用第三方库 Apache Commons CSV 或 OpenCSV 为了简化操作并提高可靠性,推荐使用成熟的第三方库来进行更复杂的数据转换工作。 #### - **Apache Commons CSV** 添加依赖(Maven配置): ```xml <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-csv</artifactId> <version>1.9.0</version> </dependency> ``` 代码示例: ```java import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVPrinter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.nio.file.Files; import java.util.Arrays; public class CsvExportExample { private static final String SAMPLE_CSV_FILE_PATH = "./data/commonsCsvFile.csv"; public static void main(String[] args) throws IOException { File file = new File(SAMPLE_CSV_FILE_PATH); Files.deleteIfExists(file.toPath()); try ( FileWriter fw = new FileWriter(SAMPLE_CSV_FILE_PATH); CSVPrinter csvFilePrinter = new CSVPrinter(fw, CSVFormat.DEFAULT.withHeader("Name", "Age", "City")); ) { // Data written using csvFilePrinter.print and .println methods csvFilePrinter.printRecord(Arrays.asList("张三","28","广州")); csvFilePrinter.printRecord(Arrays.asList("王五","46","深圳")); } } } ``` #### - **OpenCSV** 同样地,在pom.xml加入对应的依赖包引用, ```xml <dependency> <groupId>com.opencsv</groupId> <artifactId>opencsv</artifactId> <version>5.5.2</version><!-- 确保版本最新 --> </dependency> ``` 然后编写类似上面的代码逻辑即可完成任务。 这两种方案不仅支持更多的功能特性(例如自动解析列分隔符),还能有效减少编码错误几率,非常适合实际项目应用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值