Controller >
/**
* DownLoad.
*
* @param salesTransactionErrorListForm The form for this page.
* @return The name of item list page.
* @throws IOException
*/
@PostMapping(path = "/download")
public ResponseEntity<InputStreamResource> download(SalesTransactionErrorListForm salesTransactionErrorListForm)
throws IOException {
// salesTransactionErrorListService.download(salesTransactionErrorListForm);
File file = null;
try {
file = File.createTempFile("vehicle", ".csv");
} catch (IOException e1) {
e1.printStackTrace();
}
DemoCSV demo = new DemoCSV();
demo.setAmount(1);
demo.setDiscountConfigType("1");
DemoCSV demo2 = new DemoCSV();
demo2.setAmount(5);
demo2.setDiscountConfigType("1");
List<DemoCSV> ss = new ArrayList<>();
ss.add(demo2);
ss.add(demo);
try {
CsvUtility.writeAll(file, ss);
} catch (IOException e) {
System.out.println("11111111111111111");
}
try (InputStream fileStream = new ByteArrayInputStream(
FileUtils.readFileToByteArray(file))) {
HttpHeaders headers = new HttpHeaders();
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
headers.add("Content-Disposition", "attachment; filename =aa.csv");
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
InputStreamResource resource = new InputStreamResource(fileStream);
return ResponseEntity.ok()
.headers(headers)
.contentLength(FileUtils.readFileToByteArray(file).length)
.contentType(MediaType.parseMediaType("application/octet-stream"))
.body(resource);
}
}
DTO >
package com.fastretailing.dcp.sales.salestransactionerrorlist.dto;
import java.math.BigDecimal;
import java.time.OffsetDateTime;
import com.github.mygreen.supercsv.annotation.CsvBean;
import com.github.mygreen.supercsv.annotation.CsvColumn;
import lombok.Data;
/**
* File multiple buy config link age.
*/
@Data
@CsvBean(header = true)
public class DemoCSV {
/** Update time. */
@CsvColumn(number = 1, label = "eai_update_datetime")
private OffsetDateTime eaiUpdateTime;
/** Update division. */
@CsvColumn(number = 2, label = "eai_update_type")
private String eaiUpdateDivision;
/** Send status. */
@CsvColumn(number = 3, label = "eai_send_status")
private String eaiSendStatus;
/** Send time. */
@CsvColumn(number = 4, label = "eai_send_datetime")
private String eaiSendTime;
/** store Code. */
@CsvColumn(number = 5, label = "store_code")
private String storeCode;
/** Promotion code. */
@CsvColumn(number = 6, label = "promotion_code")
private String promotionCode;
/** Promotion sub code. */
@CsvColumn(number = 7, label = "promotion_sub_code")
private String promotionSubCode;
/** Apply start date. */
@CsvColumn(number = 8, label = "apply_start_date")
private OffsetDateTime applyStartDate;
/** Apply end date. */
@CsvColumn(number = 9, label = "apply_end_date")
private OffsetDateTime applyEndDate;
/** Promotion type. */
@CsvColumn(number = 10, label = "promotion_type")
private String promotionType;
/** Amount. */
@CsvColumn(number = 11, label = "amount")
private Integer amount;
/** Success price. */
@CsvColumn(number = 12, label = "success_price")
private BigDecimal successPrice;
/** Discount type. */
@CsvColumn(number = 13, label = "multi_buy_discount_type")
private String discountType;
/** Customer flag. */
@CsvColumn(number = 14, label = "customer_flag")
private String customerFlag;
/** Discount config type. */
@CsvColumn(number = 15, label = "discount_config_type")
private String discountConfigType;
/** System business code. */
@CsvColumn(number = 16, label = "system_business_code")
private String systemBusinessCode;
/** System brand code. */
@CsvColumn(number = 17, label = "system_brand_code")
private String systemBrandCode;
/** System country code. */
@CsvColumn(number = 18, label = "system_country_code")
private String systemCountryCode;
}
Util >
package com.fastretailing.dcp.sales.salestransactionerrorlist.utils;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.List;
import org.supercsv.prefs.CsvPreference;
import org.supercsv.quote.AlwaysQuoteMode;
import com.github.mygreen.supercsv.io.CsvAnnotationBeanWriter;
public class CsvUtility {
private CsvUtility() {}
/**
* Write all data to csv file.
*
* @param fullFileName Output file name.
* @param dataList List of data(super-csv annotation CsvBean and CsvColumn).
* @param dataType Type of list elements.(No setting required)
* @throws IOException If an I/O error occurs.
*/
@SuppressWarnings("unchecked")
public static <T> void writeAll(String fullFileName, List<T> dataList, T... dataType)
throws IOException {
// Get data type.
Class<T> classType = (Class<T>) dataType.getClass().getComponentType();
writeAllImpl(Paths.get(fullFileName), dataList, classType);
return;
}
/**
* Write all data to csv file.
*
* @param writeFile
* @param dataList List of data(super-csv annotation CsvBean and CsvColumn).
* @param dataType Type of list elements.(No setting required)
* @throws IOException If an I/O error occurs.
*/
@SuppressWarnings("unchecked")
public static <T> void writeAll(File writeFile, List<T> dataList, T... dataType)
throws IOException {
// Get data type.
Class<T> classType = (Class<T>) dataType.getClass().getComponentType();
writeAllImpl(Paths.get(writeFile.toURI()), dataList, classType);
return;
}
/**
* Write all data to csv file.
*
* @param writeFilePath Output file path.
* @param dataList List of data(super-csv annotation CsvBean and CsvColumn).
* @param classType Type of list elements.
* @throws IOException If an I/O error occurs.
*/
private static <T> void writeAllImpl(Path writeFilePath, List<T> dataList, Class<T> classType)
throws IOException {
// Build csv preference
CsvPreference csvPreference = new CsvPreference.Builder(CsvPreference.STANDARD_PREFERENCE)
.useQuoteMode(new AlwaysQuoteMode())
.build();
// Write csv.
try (CsvAnnotationBeanWriter<T> csvWriter =
new CsvAnnotationBeanWriter<>(classType, Files.newBufferedWriter(writeFilePath,
StandardCharsets.UTF_8, StandardOpenOption.CREATE), csvPreference)) {
csvWriter.writeAll(dataList);
}
return;
}
}
---------------------------------------
POM>
<dependency>
<groupId>com.github.mygreen</groupId>
<artifactId>super-csv-annotation</artifactId>
<version>2.1</version>
</dependency>