Last active
September 2, 2022 09:28
-
-
Save hnaohiro/2f33696a30a09e8ba6afcfde28042a46 to your computer and use it in GitHub Desktop.
POIでExcelのセルの書式を金額型にする
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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