Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
KotlinでExcelにQRコードを描く
package link.arata.kexcel
import com.google.zxing.BarcodeFormat
import com.google.zxing.EncodeHintType
import com.google.zxing.client.j2se.MatrixToImageWriter
import com.google.zxing.qrcode.QRCodeWriter
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel
import link.arata.kexcelapi.get
import org.apache.poi.ss.usermodel.CellStyle
import org.apache.poi.xssf.usermodel.XSSFColor
import org.apache.poi.xssf.usermodel.XSSFWorkbook
import java.awt.Color
import java.io.File
import java.util.*
fun main(args: Array<String>) {
var workbook: XSSFWorkbook = XSSFWorkbook()
var sheet = workbook.createSheet()
workbook.setSheetName(0, "QRコード")
sheet.setDisplayGridlines(false)
val contents = "http://webarata.hatenablog.jp"
val format = BarcodeFormat.QR_CODE
val width = 40
val height = width
val rowHeight = 500f / width
val hints = Hashtable<EncodeHintType, ErrorCorrectionLevel>()
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M)
val writer = QRCodeWriter()
val bitMatrix = writer.encode(contents, format, width, height, hints)
val image = MatrixToImageWriter.toBufferedImage(bitMatrix);
for (y in 0..height - 1) {
sheet[y].heightInPoints = rowHeight
}
for (x in 0..width - 1) {
sheet.setColumnWidth(x, (rowHeight * 41f).toInt())
}
val style = workbook.createCellStyle()
style.fillPattern = CellStyle.SOLID_FOREGROUND
style.setFillForegroundColor(XSSFColor(Color(0, 0, 0)))
for (y in 0..height - 1) {
for (x in 0..width - 1) {
if (image.getRGB(x, y) == -16777216) {
sheet[x, y].cellStyle = style
}
}
}
workbook.write(File("image.xlsx").outputStream());
workbook.close()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment