springboot导出数据到csv文件并进行压缩
时间: 2023-12-22 17:06:15 浏览: 173
以下是使用Spring Boot将数据导出到CSV文件并进行压缩的示例:
1. 添加依赖项
在 pom.xml 文件中添加以下依赖项:
```xml
<dependency>
<groupId>com.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>5.5.2</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-compress</artifactId>
<version>1.21</version>
</dependency>
```
2. 创建CSV文件
使用 OpenCSV 库创建 CSV 文件。在本例中,我们将使用以下数据作为示例:
```java
List<String[]> data = new ArrayList<>();
data.add(new String[]{"Name", "Age", "Email"});
data.add(new String[]{"John", "30", "john@example.com"});
data.add(new String[]{"Jane", "25", "jane@example.com"});
data.add(new String[]{"Mike", "35", "mike@example.com"});
```
创建 CSV 文件的代码如下:
```java
CSVWriter writer = new CSVWriter(new FileWriter("data.csv"));
writer.writeAll(data);
writer.close();
```
3. 压缩CSV文件
使用 Apache Commons Compress 库将生成的 CSV 文件压缩为 zip 文件。以下是将 CSV 文件压缩为 zip 文件的代码:
```java
FileInputStream inputStream = new FileInputStream("data.csv");
ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream("data.zip"));
ZipEntry zipEntry = new ZipEntry("data.csv");
zipOutputStream.putNextEntry(zipEntry);
byte[] bytes = new byte[1024];
int length;
while ((length = inputStream.read(bytes)) >= 0) {
zipOutputStream.write(bytes, 0, length);
}
zipOutputStream.closeEntry();
zipOutputStream.close();
inputStream.close();
```
4. 完整代码
以下是将数据导出到 CSV 文件并进行压缩的完整代码:
```java
import com.opencsv.CSVWriter;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class CsvExporter {
public static void main(String[] args) throws IOException {
List<String[]> data = new ArrayList<>();
data.add(new String[]{"Name", "Age", "Email"});
data.add(new String[]{"John", "30", "john@example.com"});
data.add(new String[]{"Jane", "25", "jane@example.com"});
data.add(new String[]{"Mike", "35", "mike@example.com"});
CSVWriter writer = new CSVWriter(new FileWriter("data.csv"));
writer.writeAll(data);
writer.close();
FileInputStream inputStream = new FileInputStream("data.csv");
ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream("data.zip"));
ZipEntry zipEntry = new ZipEntry("data.csv");
zipOutputStream.putNextEntry(zipEntry);
byte[] bytes = new byte[1024];
int length;
while ((length = inputStream.read(bytes)) >= 0) {
zipOutputStream.write(bytes, 0, length);
}
zipOutputStream.closeEntry();
zipOutputStream.close();
inputStream.close();
}
}
```
此代码将生成名为 `data.zip` 的压缩文件,其中包含名为 `data.csv` 的 CSV 文件。
阅读全文