Skip to content

Instantly share code, notes, and snippets.

@hnaohiro
Last active September 2, 2022 09:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hnaohiro/2f33696a30a09e8ba6afcfde28042a46 to your computer and use it in GitHub Desktop.
Save hnaohiro/2f33696a30a09e8ba6afcfde28042a46 to your computer and use it in GitHub Desktop.
POIでExcelのセルの書式を金額型にする
import org.apache.poi.ss.usermodel.WorkbookFactory
import org.apache.poi.xssf.usermodel.XSSFWorkbook
import java.io.FileInputStream
import java.io.FileOutputStream
fun main(args: Array<String>) {
val path = "test.xlsx"
write(path)
read(path)
}
fun write(path: String) {
val wb = XSSFWorkbook();
val format = wb.createDataFormat();
val sheet = wb.createSheet();
val row = sheet.createRow(0);
val cell = row.createCell(0);
val style = wb.createCellStyle();
style.dataFormat = format.getFormat("\"¥\"#,##0");
cell.cellStyle = style;
cell.setCellValue(12345.toDouble()) // Stringとして入れると、フォーマットが効かない (例: "12345")
val output = FileOutputStream(path)
wb.write(output)
}
fun read(path: String) {
val input = FileInputStream(path)
val wb = WorkbookFactory.create(input)
val sheet = wb.getSheetAt(0)
val row = sheet.getRow(0)
val cell = row.getCell(0)
println(cell.numericCellValue.toInt())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment