Skip to content

Commit

Permalink
Merge pull request #10 from team-xquare/9-get-info-DB-to-Excel
Browse files Browse the repository at this point in the history
🔀 :: (XQUARE-9)get info db to excel API
  • Loading branch information
meltapplee authored Jan 26, 2024
2 parents 6835a79 + ab3cde7 commit f0de145
Show file tree
Hide file tree
Showing 7 changed files with 165 additions and 18 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.xaquare.xquarebackoffice.infrastructure.excel.controller

import com.xaquare.xquarebackoffice.infrastructure.excel.service.CreateExcelSheetAsDB
import com.xaquare.xquarebackoffice.infrastructure.excel.service.CreateExcelSheetService
import com.xaquare.xquarebackoffice.infrastructure.excel.service.GetExcelSheetService

Expand All @@ -14,7 +15,8 @@ import javax.servlet.http.HttpServletResponse
@RequestMapping("/excel")
class ExcelController(
private val createExcelSheetService: CreateExcelSheetService,
private val getExcelSheetService: GetExcelSheetService
private val getExcelSheetService: GetExcelSheetService,
private val createExcelSheetAsDB: CreateExcelSheetAsDB
) {
@GetMapping
fun createExcelSheet(httpServletResponse: HttpServletResponse) =
Expand All @@ -23,4 +25,8 @@ class ExcelController(
@PostMapping
fun saveExcelInfo(file: MultipartFile) =
getExcelSheetService.execute(file)

@GetMapping("/userInfo")
fun createExcelSheetAsDD(httpServletResponse: HttpServletResponse) =
createExcelSheetAsDB.excute(httpServletResponse)
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ package com.xaquare.xquarebackoffice.infrastructure.excel.dto

data class ExcelData (
val name: String,
val entranceYear: String,
val entranceYear: Int,
val birthDay: String,
val grade: String,
val classNum: String,
val num: String
)
val grade: Int,
val classNum: Int,
val num: Int
)
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,4 @@ import com.xaquare.xquarebackoffice.global.error.exception.XquareException

object DBAccessException : XquareException(
ErrorCode.DB_ACCESS_ERROR
)
)
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,4 @@ import com.xaquare.xquarebackoffice.global.error.exception.XquareException

object DataFormatException : XquareException(
ErrorCode.DATA_FORMAT_BAD_REQUEST
)
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
package com.xaquare.xquarebackoffice.infrastructure.excel.service

import com.xaquare.xquarebackoffice.infrastructure.excel.ExcelProperties
import com.xaquare.xquarebackoffice.infrastructure.excel.dto.ExcelData
import com.xaquare.xquarebackoffice.infrastructure.excel.service.query.ExcelQuery
import org.apache.poi.ss.usermodel.*
import org.apache.poi.xssf.usermodel.XSSFWorkbook
import org.springframework.stereotype.Service
import java.sql.Connection
import java.sql.DriverManager
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import javax.servlet.http.HttpServletResponse

@Service
class CreateExcelSheetAsDB(
private val properties: ExcelProperties,
private val query: ExcelQuery

) {
fun excute(response: HttpServletResponse) {

val workbook: Workbook = XSSFWorkbook()
val sheet: Sheet = workbook.createSheet("xquare_userInfo").apply {
defaultColumnWidth = 30
}

val headerCellStyle: CellStyle = workbook.createCellStyle().apply {
setBorderStyle(BorderStyle.THIN)
fillForegroundColor = IndexedColors.BLACK1.index
fillPattern = FillPatternType.SOLID_FOREGROUND
setFont(workbook.createFont().apply {
color = IndexedColors.WHITE.index
})
}

val headerNames = arrayOf("이름", "입학년도", "생일", "학년", "", "번호")

val headerRow: Row = sheet.createRow(0)
headerNames.forEachIndexed { i, header ->
val headerCell: Cell = headerRow.createCell(i).apply {
setCellValue(header)
cellStyle = headerCellStyle
}
}

//Body
val bodyCellStyle: CellStyle = workbook.createCellStyle().apply {
setBorderStyle(BorderStyle.THIN)
}

val bodyData = arrayOf(
arrayOf("예시) 홍길동", "예시) 2023", "예시) 2024,01,01", "예시) 1", "예시) 1", "예시) 1"),
)

bodyData.forEachIndexed { i, bodyRowData ->
val bodyRow: Row = sheet.createRow(i + 1)
bodyRowData.forEachIndexed { j, data ->
val bodyCell: Cell = bodyRow.createCell(j).apply {
setCellValue(data)
cellStyle = bodyCellStyle
}
}
}

val dataList: MutableList<ExcelData> = ArrayList()
val jdbcUrl = "jdbc:mysql://${properties.host}:${properties.port}/${properties.database}"
val username = properties.username
val password = properties.password

var connection: Connection? = null

try {
connection = DriverManager.getConnection(jdbcUrl, username, password)

val query = "${query.selectQuery()} ${properties.database}"
val statement = connection.createStatement()
val sqlResult = statement.executeQuery(query)

while (sqlResult.next()) {
val data = ExcelData(
name = sqlResult.getString("name"),
entranceYear = sqlResult.getInt("entrance_year"),
birthDay = sqlResult.getString("birth_day"),
grade = sqlResult.getInt("grade"),
classNum = sqlResult.getInt("class_num"),
num = sqlResult.getInt("num")
)
dataList.add(data)
}
} finally {
connection?.close()
}

dataList.forEachIndexed { i, data ->
val row: Row = sheet.createRow(i + 2).apply {
createCell(0).setCellValue(data.name)
createCell(1).setCellValue((data.entranceYear).toDouble())
createCell(2).setCellValue(formatBirthday(data.birthDay))
createCell(3).setCellValue((data.grade).toDouble())
createCell(4).setCellValue((data.classNum).toDouble())
createCell(5).setCellValue((data.num).toDouble())
forEach { cell ->
cell.cellStyle = bodyCellStyle
}
}

row.forEach { cell ->
cell.cellStyle = bodyCellStyle
}
}

val fileName = "xquare_userInfo.spreadsheetml_download"
response.contentType = "application/xquare_userInfo.spreadsheetml.sheet"
response.setHeader("Content-Disposition", "attachment;filename=$fileName.xlsx")
val servletOutputStream = response.outputStream

workbook.write(servletOutputStream)
workbook.close()
servletOutputStream.flush()
servletOutputStream.close()
}

private fun CellStyle.setBorderStyle(style: BorderStyle) {
borderLeft = style
borderRight = style
borderTop = style
borderBottom = style
}

private fun formatBirthday(birthday: String): String {
val originalString = LocalDate.parse(birthday, DateTimeFormatter.ISO_DATE)
return originalString.format(DateTimeFormatter.ofPattern("yyyy,MM,dd"))
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -49,11 +49,11 @@ class GetExcelSheetService(

val excelData = ExcelData(
name = row.getCell(0).stringCellValue.toString(),
entranceYear = row.getCell(1).numericCellValue.toInt().toString(),
entranceYear = row.getCell(1).numericCellValue.toInt(),
birthDay = getLocalDateFromString(row.getCell(2).toString())?.toString() ?: "",
grade = row.getCell(3).numericCellValue.toInt().toString(),
classNum = row.getCell(4).numericCellValue.toInt().toString(),
num = row.getCell(5).numericCellValue.toInt().toString(),
grade = row.getCell(3).numericCellValue.toInt(),
classNum = row.getCell(4).numericCellValue.toInt(),
num = row.getCell(5).numericCellValue.toInt(),
)
dataList.add(excelData)
}
Expand All @@ -76,17 +76,17 @@ class GetExcelSheetService(
connection.autoCommit = false

val sql = excelQuery.executeQuery()

preparedSql = connection.prepareStatement(sql)

preparedSql.apply {
for (excelData in dataList) {
setString(1, excelData.name)
setString(2, excelData.entranceYear)
setInt(2, excelData.entranceYear)
setString(3, excelData.birthDay)
setString(4, excelData.grade)
setString(5, excelData.classNum)
setString(6, excelData.num)
setInt(4, excelData.grade)
setInt(5, excelData.classNum)
setInt(6, excelData.num)
addBatch()
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,10 @@ class ExcelQuery {
VALUES (?, ?, ?, ?, ?, ?)
"""
}
}

fun selectQuery(): String {
return """
SELECT * FROM
""".trimIndent()
}
}

0 comments on commit f0de145

Please sign in to comment.