Coding Planet
[Java]CSV ํ์ผ ์์ฑ ํด๋์ค ์์ ๋ณธ๋ฌธ
๋ฐ์ํ
| writeListToCSVFile ๋ฉ์๋๋ฅผ ํธ์ถํ์ฌ ํ์ผ์ ์์ฑ
- ํด๋น ํด๋์ค๋ ์ ๋ชฉํ(header row)์ ๋ด์ฉํ(data row)๋ฅผ ๊ฐ๊ฐ ๋ถ๋ฆฌํ์ฌ ์์ฑํ๋ค.
- fileName : ๊ฒฝ๋ก๋ฅผ ํฌํจํ ํ์ผ์ด๋ฆ(ex. /portal/upload/DATA_202305240323420290)
- headerlist : ์ ๋ชฉํ
- dataList : ๋ด์ฉํ
- dataList ์์ฒด๋ ์ปฌ๋ผ๊ณผ ๋ฐ์ดํฐ๋ก ์ง์ง์ด ์์ง๋ง ์ค์ ํ์ผ ์์ฑ์ ๋ฐ์ดํฐ๋ง์ ์ฌ์ฉํ๋ค. ์ฆ ์ ๋ชฉํ์ ๋นจ๊ฐ, ํ๋, ๋ ธ๋์ด๊ณ ๋ฐ์ดํฐ 1, ๋ฐ์ดํฐ2, ๋ฐ์ดํฐ3์ด ์์ธ๋ค.
List<String> headers = Arrays.asList("๋นจ๊ฐ", "ํ๋", "๋
ธ๋");
List<Map<String, String>> data = new ArrayList<>();
Map<String, String> row1 = new HashMap<>();
row1.put("์ปฌ๋ผ1", "๋ฐ์ดํฐ1");
row1.put("์ปฌ๋ผ2", "๋ฐ์ดํฐ2");
row1.put("์ปฌ๋ผ3", "๋ฐ์ดํฐ3");
data.add(row1);
DataCSVUtil.writeListToCSVFile("output.csv", headers, data);โ
package chungnam.jobutil;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.List;
import java.util.Map;
public class DataCSVUtil {
public static void writeListToCSVFile(String fileName, List<String> headerList, List<Map<String, String>> dataList) {
Writer writer = null;
try {
writer = new OutputStreamWriter(new FileOutputStream(fileName), "UTF-8");
// Write BOM for UTF-8
writer.write('\uFEFF');
// Header row
for (int i = 0; i < headerList.size(); i++) {
writer.append(escapeSpecialCharacters(headerList.get(i)));
if (i < headerList.size() - 1) {
writer.append(",");
}
}
writer.append("\n");
// Write the data rows
for (Map<String, String> data : dataList) {
int cellIndex = 0;
for (String key : data.keySet()) {
String value = (String) data.values().toArray()[cellIndex++];
writer.append(escapeSpecialCharacters(value != null ? value : ""));
if (cellIndex < data.size()) {
writer.append(",");
}
}
writer.append("\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (writer != null) {
writer.flush();
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static String escapeSpecialCharacters(String data) {
if (data == null) {
return "";
}
String escapedData = data.replace("\"", "\"\"");
if (data.contains(",") || data.contains("\n") || data.contains("\"")) {
escapedData = "\"" + escapedData + "\"";
}
return escapedData;
}
}
๋ฐ์ํ
Comments