从数据库导出csv文件
从HeidiSQL 导数据出来成.csv文件
SELECT * FROM csv INTO OUTFILE 'C:\\feiniu\\note\\csv\\demo.csv' fields terminated by ','
CSV是什么
跟Excel表差不多
csv与excel对比:
- csv只能用于存储纯文本内容,excel不仅支持纯文本内容还支持二进制数据
- csv可以看做是excel的轻量级简单版实现,excel比csv更加强大
- csv文件可以被excel软件直接打开,csv文件一般用于表格数据的传输
纯文本形式存储表格数据,分隔字符有:逗号、分号 空格等
每行一条记录
关于操作csv文件
- 读取CSV 文件转Java对象
- CSV转Excel
- CSV转对象后存数据库
- 下载(导出)CSV文件
依赖:opencsv、easyexcel
导出Java对象转CSV导出文件
maven: OpenCSV
<dependency>
<groupId>com.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>5.6</version>
</dependency>
controller
@RestController
@Slf4j
@RequestMapping("/file")
public class FileController extends BaseController{
@Autowired
private FileService fileService;
@PostMapping("/downloadUserListCsv")
public void downloadUserListCsv(HttpServletResponse response) {
fileService.downUserListCsv(DownloadPublicUtil.UserListCsvHeader, response);
}
}
service
@Service
public class FileServiceImpl implements FileService {
@Override
public void downUserListCsv(String[] head, HttpServletResponse response) {
List<User> userList = List.of(
User.builder().userId("1").userName("张三").sex("男").build(),
User.builder().userId("2").userName("李四").sex("男").build(),
User.builder().userId("3").userName("王五").sex("男").build()
);
ExportCsvUtils.exportCsv(head,userList,User.class,"user-list-1",response);
}
}
utils
ExportCsvUtils
public class ExportCsvUtils {
private ExportCsvUtils(){
}
public static <T> void exportCsv(String[] headers, List<T> list, Class c, String fileName, HttpServletResponse response){
OutputStream outputStream = null;
CSVWriter csvWriter = null;
try {
DownloadPublicUtil.setResponse(response, FileTypeEnum.CSV,
fileName, DownloadCharsetEnum.WINDOWS_1252);
outputStream = response.getOutputStream();
// prevent from turning Chinese into garbled code
outputStream.write(0xEF);
outputStream.write(0xBB);
outputStream.write(0xBF);
// outputStream = response.getOutputStream();
csvWriter = new CSVWriter(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8));
//写入标题行
csvWriter.writeNext(headers);
Map<String, String> map = new HashMap<>();
Field[] declaredFields = c.getDeclaredFields();
// each row
for (T t : list) {
for (Field declaredField : declaredFields){
declaredField.setAccessible(true);
Object o = null;
try {
o = declaredField.get(t);
if (o instanceof String){
// userId -> UserId
String fieldName = declaredField.getName();
String firstChar = fieldName.substring(0, 1).toUpperCase();
fieldName = firstChar + fieldName.substring(1);
map.put(fieldName,(String) o);
}
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
ArrayList<String> values = new ArrayList<>();
for(String header : headers){
//User Id -> UserId
header = header.replace(" ","");
String value = map.get(header);
values.add(value);
}
// 写入数据行
csvWriter.writeNext(values.toArray(new String[0]));
csvWriter.flush();
}
} catch (IOException e) {
throw new RuntimeException(e);
}finally {
try {
if (csvWriter != null) {
csvWriter.close();
}
if (outputStream != null) {
outputStream.close();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
DownloadPublicUtil
public class DownloadPublicUtil {
public static String[] UserListCsvHeader = {"User Id","User Name","Sex"};
private DownloadPublicUtil(){
}
public static void setResponse(HttpServletResponse response, FileTypeEnum fileTypeEnum, String fileName, DownloadCharsetEnum charsets) {
fileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8).replaceAll("\\+", "%20");
response.reset();
response.setCharacterEncoding(charsets.getVal());
if (fileTypeEnum.equals(FileTypeEnum.CSV)) {
response.setContentType("text/" + fileTypeEnum + ";charset=" + charsets.getVal());
} else {
response.setContentType("application/" + fileTypeEnum + ";charset=" + charsets.getVal());
}
response.setHeader("Content-Disposition", "attachment; filename=" + fileName + fileTypeEnum.getSuffix());
}
}
enum
@Getter
@AllArgsConstructor
public enum DownloadCharsetEnum {
UTF_8("utf-8"),
WINDOWS_1252("windows-1252");
private final String val;
}
@Getter
public enum FileTypeEnum {
EXCEL(".xlsx"),
PDF(".pdf"),
CSV(".csv");
private final String suffix;
FileTypeEnum(String suffix) {
this.suffix = suffix;
}
}
没设置response