발주기관건설현장 엑셀다운로드 처리

main
유지인 2025-12-17 16:34:15 +09:00
parent a638db7d58
commit 7366d26a6a
5 changed files with 703 additions and 55 deletions

View File

@ -3,15 +3,21 @@ package geoinfo.admins.constructionProjectManagement;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date; import java.util.Date;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Locale;
import java.util.Map; import java.util.Map;
import javax.annotation.Resource; import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.json.simple.JSONArray; import org.json.simple.JSONArray;
import org.json.simple.JSONObject; import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser; import org.json.simple.parser.JSONParser;
@ -30,8 +36,10 @@ import geoinfo.admins.constructionProjectManagement.service.ConstructionProjectM
import geoinfo.admins.user.service.DrillingInquiryService; import geoinfo.admins.user.service.DrillingInquiryService;
import geoinfo.admins.user.service.GeneralUserMngService; import geoinfo.admins.user.service.GeneralUserMngService;
import geoinfo.admins.user.service.HomeTrainingService; import geoinfo.admins.user.service.HomeTrainingService;
import geoinfo.com.EgovExcel;
import geoinfo.comm.util.strUtil; import geoinfo.comm.util.strUtil;
import geoinfo.session.UserInfo; import geoinfo.session.UserInfo;
import geoinfo.util.ExcelMergeHeaderUtil;
import geoinfo.util.MyUtil; import geoinfo.util.MyUtil;
@Controller @Controller
@ -738,7 +746,7 @@ public class ConstructionProjectManagementController {
JSONObject jSONOResponse = null; JSONObject jSONOResponse = null;
try { try {
jSONOResponse = drillingInquiryService.drillingInquiryList( request, params ); jSONOResponse = drillingInquiryService.drillingInquiryList( request, params );
} catch (Exception e) { } catch (Exception e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
jSONOResponse = new JSONObject(); jSONOResponse = new JSONObject();
@ -786,7 +794,52 @@ public class ConstructionProjectManagementController {
return null; return null;
} }
/**
* CSV
* @param workbook
* @param request
* @param response
* @throws Exception
*/
@RequestMapping(value = "admins/drilling/inquiry/excel.do")
public void downloadDrillingInquiryListExcel(HttpServletRequest request, HttpServletResponse response, HSSFWorkbook workbook, @RequestParam HashMap<String, Object> params) throws Exception {
HashMap<String, Object> map = new HashMap<String, Object>();
String[] headers = {"cid","constName","projectStateCodeName","constStartDate","constStateCodeName","masterCompanyDept","masterCompanyAdmin","masterCompanyTel","coinstCompanyDept","constCompanyAdmin","constCompanyTel"};
String[][] headerNames = {{"연번", "사업명", "입력상태", "사업내용", "", "", "발주기관현황", "", "", "건설사현황", ""},
{"", "", "", "사업기간", "사업단계", "담당부서", "담당자", "담당자연락처", "건설사명", "담당자", "담당자연락처"}};
final int[] headerWidths = {1325, 15900, 4240, 6360, 5830, 6890, 2915, 3710, 5035, 2915, 3710};
String[] columnType = {"String", "String", "String", "String", "String", "String", "String", "String", "String", "String", "String"};
String sheetName = "Sheet1";
String excelFileName = "발주기관 건설현장 목록";
// int startIndex = 0;
Long totalCount = 0L;
// DB 조회
JSONObject resultObj = drillingInquiryService.drillingInquiryList(request, params);
// 여기에서 list 꺼내기
List<EgovMap> list = (List<EgovMap>) resultObj.get("datas");
totalCount = (Long) resultObj.get("count");
int idx = 0;
for (EgovMap rowData : list) {
// 공사기간 형식 처리: startDate ~ endDate
String constStartDate = (String) rowData.get("constStartDate");
String constEndDate = (String) rowData.get("constEndDate");
rowData.put("constStartDate", constStartDate + " ~ " + constEndDate); // 공사기간을 'startDate ~ endDate' 형식으로 변환
rowData.put("cid", (totalCount) - (idx++));
}
ExcelMergeHeaderUtil.listToExcelMergeHeader(list, response, headers, headerNames, headerWidths, columnType, sheetName, excelFileName);
}
/** /**
* > * >
* @param params * @param params
@ -839,5 +892,23 @@ public class ConstructionProjectManagementController {
return "admins/constructionProjectManagement/construction-user-login-history"; return "admins/constructionProjectManagement/construction-user-login-history";
} }
public void buildExcelDocument(Map<String, Object> model, HSSFWorkbook workbook, HttpServletRequest request, HttpServletResponse response) throws Exception {
List<?> selectInfoListExcel = (List<?>) model.get("selectInfoListExcel");
String[] arrHeader = (String[]) model.get("arrHeader");
Sheet sheet = workbook.createSheet((String) model.get("sheetName"));
EgovExcel.SetExcelList(workbook, sheet, arrHeader, selectInfoListExcel, 0, 0);
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-disposition",
"attachment;filename=" + URLEncoder.encode((String) model.get("fileName") + (new SimpleDateFormat("yyyy.MM.dd", Locale.KOREA)).format(new Date()), "UTF-8")
+ ".xls" + ";");
ServletOutputStream myOut = response.getOutputStream();
workbook.write(myOut); // 파일 저장
}
} }

View File

@ -118,6 +118,8 @@ public class DrillingInquiryServiceImpl implements DrillingInquiryService {
JSONObject jsonResponse = new JSONObject(); JSONObject jsonResponse = new JSONObject();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String userId = MyUtil.getStringFromObject( params.get("userId") ); String userId = MyUtil.getStringFromObject( params.get("userId") );
String excelDownload = MyUtil.getStringFromObject( params.get("excelDownload") );
String masterCompanyOCode = ""; String masterCompanyOCode = "";
String masterCompanyTwCode = ""; String masterCompanyTwCode = "";
String masterCompanyThCode = ""; String masterCompanyThCode = "";
@ -164,6 +166,9 @@ public class DrillingInquiryServiceImpl implements DrillingInquiryService {
Long count = drillingInquiryMapper.sPCntTblCsiByKeyword(params); Long count = drillingInquiryMapper.sPCntTblCsiByKeyword(params);
if ("Y".equals(excelDownload)) {
params.put("nCount", count);
}
List<EgovMap> datas = drillingInquiryMapper.spGetTblCsiByKeyword(params); List<EgovMap> datas = drillingInquiryMapper.spGetTblCsiByKeyword(params);

View File

@ -0,0 +1,548 @@
package geoinfo.util;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFDataFormat;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.ss.usermodel.Font;
import egovframework.rte.psl.dataaccess.util.EgovMap;
public class ExcelMergeHeaderUtil {
public static boolean isEmpty(final Object obj) {
return !isNotEmpty(obj);
}
public static boolean isNotEmpty(final Object obj) {
if(null == obj) return false;
else {
if(obj instanceof String) return "".equals(obj) ? false : true;
else if(obj instanceof List) return !((List<?>)obj).isEmpty();
else if(obj instanceof Map) return !((Map<?,?>)obj).isEmpty();
// else if(obj instanceof Object[]) return 0 == Array.getLength(obj) ? false : true;
else if(obj instanceof Integer) return !(null == obj);
else if(obj instanceof Long) return !(null == obj);
else if(obj instanceof LocalDate) return !(null == obj);
else return false;
}
}
public static String getTimeStampString(final String format) {
return getTimeStampString(new Date(), format);
}
public static String getTimeStampString(final Date date) {
return getTimeStampString(date, "yyyyMMddHHmmss");
}
public static String getTimeStampString(final Date date, final String format){
java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat (format, java.util.Locale.KOREA);
return formatter.format(date);
}
public static String getTimeStampString(String date, final String format) {
try {
if(null == date || "".equals(date)) return "";
Date d = null;
date= date.replaceAll("-", "");
switch(date.length()) {
case 14: break;
case 12: date += "00"; break;
case 10: date += "0000"; break;
case 8: date += "000000"; break;
case 6: date += "01000000"; break;
case 4: date += "0101000000"; break;
default: return "";
}
java.text.SimpleDateFormat tmpFormat = new java.text.SimpleDateFormat("yyyyMMddHHmmss", java.util.Locale.KOREA);
if("".equals(date)) d = new Date();
else {
tmpFormat.setLenient(true);
d = tmpFormat.parse(date);
}
return getTimeStampString(d, format);
} catch(Exception e) {
e.printStackTrace();
return "";
}
}
public static String getFileExtention(final String filename) {
if(null == filename || "".equals(filename)) return "";
return -1 < filename.lastIndexOf(".") ? filename.substring(filename.lastIndexOf(".") + 1).toLowerCase() : "";
}
public static String generationSaveName() {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
return ExcelMergeHeaderUtil.getTimeStampString("yyyyMMdd_HHmmss_SSS");
}
public static void listToExcel(List<ParamMap> list, HttpServletResponse response, String[] headers, String[] headerNames, String[] columnType, String sheetName, String excelFileName) throws IOException {
if(ExcelMergeHeaderUtil.isNotEmpty(list)) {
// 메모리에 100개의 행을 유지합니다. 행의 수가 넘으면 디스크에 적습니다.
XSSFWorkbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet(sheetName);
Row headerRow = sheet.createRow(0);
CellStyle cellStyle1 = wb.createCellStyle(); //쉼표들어간 숫자 양식
CellStyle cellStyle2 = wb.createCellStyle(); //숫자양식
CellStyle headerStyle = wb.createCellStyle(); //숫자양식
XSSFDataFormat format = wb.createDataFormat();
cellStyle1.setDataFormat(format.getFormat("#,##0"));
cellStyle2.setDataFormat(format.getFormat("#"));
headerStyle.setAlignment(HorizontalAlignment.CENTER);
headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
headerStyle.setFillForegroundColor((short)3);
headerStyle.setFillForegroundColor(IndexedColors.LIME.getIndex());
for(int i=0; i<list.size(); i++) {
ParamMap rowData = list.get(i);
Row row = sheet.createRow(i+1);
for(int j=0; j<headers.length; j++) {
Cell cell = row.createCell(j);
if(columnType[j].equalsIgnoreCase("Money")) {
cell.setCellValue(rowData.getInt(headers[j]));
cell.setCellStyle(cellStyle1);
} else if(columnType[j].equalsIgnoreCase("Int")) {
cell.setCellValue(rowData.getInt(headers[j]));
cell.setCellStyle(cellStyle2);
} else if(columnType[j].equalsIgnoreCase("String")) {
cell.setCellValue(rowData.getString(headers[j]));
} else {
cell.setCellValue(rowData.getString(headers[j]));
}
}
}
for(int j=0; j<headerNames.length; j++) {
Cell cell = headerRow.createCell(j);
cell.setCellValue(headerNames[j]);
cell.setCellStyle(headerStyle);
sheet.autoSizeColumn(j);
sheet.setColumnWidth(j, (sheet.getColumnWidth(j)) + 1000);
}
//엑셀이름 한글깨짐방지
String outputFileName = new String(excelFileName.getBytes("KSC5601"), "8859_1");
response.setHeader("Set-Cookie", "fileDownload=true; path=/");
response.setHeader("Content-Disposition", String.format("attachment; filename=\""+outputFileName+"_"+ExcelMergeHeaderUtil.getTimeStampString("yyyyMMdd_HHmm")+".xlsx\""));
wb.write(response.getOutputStream());
wb.close();
} else {
createNoDataAlert(response);
}
}
public static void listToExcelMergeHeader(List<EgovMap> list, HttpServletResponse response, String[] headers, String[][] headerNames, int[] headerWidths, String[] columnType, String sheetName, String excelFileName) throws IOException {
if(ExcelMergeHeaderUtil.isNotEmpty(list)) {
// 메모리에 100개의 행을 유지합니다. 행의 수가 넘으면 디스크에 적습니다.
XSSFWorkbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet(sheetName);
Row headerRow = sheet.createRow(headerNames.length);
CellStyle cellStyle1 = wb.createCellStyle(); //쉼표들어간 숫자 양식
CellStyle cellStyle2 = wb.createCellStyle(); //숫자양식
CellStyle headerStyle = wb.createCellStyle(); //헤더 스타일
CellStyle borderStyle = wb.createCellStyle(); // 기본 검정 테두리 스타일
// 기본 검정 테두리 스타일 설정
borderStyle.setBorderTop(BorderStyle.THIN);
borderStyle.setBorderBottom(BorderStyle.THIN);
borderStyle.setBorderLeft(BorderStyle.THIN);
borderStyle.setBorderRight(BorderStyle.THIN);
// 글꼴 색상 흰색으로 설정
Font headerFont = wb.createFont();
headerFont.setColor(IndexedColors.WHITE.getIndex()); // 글씨 색상 흰색
headerStyle.setFont(headerFont); // 헤더 스타일에 적용
XSSFDataFormat format = wb.createDataFormat();
cellStyle1.setDataFormat(format.getFormat("#,##0"));
cellStyle2.setDataFormat(format.getFormat("#"));
headerStyle.setBorderTop(BorderStyle.THIN);
headerStyle.setBorderBottom(BorderStyle.THIN);
headerStyle.setBorderLeft(BorderStyle.THIN);
headerStyle.setBorderRight(BorderStyle.THIN);
headerStyle.setAlignment(HorizontalAlignment.CENTER);
headerStyle.setVerticalAlignment(VerticalAlignment.CENTER);
headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
// headerStyle.setFillForegroundColor((short)3);
headerStyle.setFillForegroundColor(IndexedColors.GREY_40_PERCENT.getIndex());
// 바디 스타일
CellStyle bodyStyle = wb.createCellStyle();
bodyStyle.setAlignment(HorizontalAlignment.CENTER);
// ---------- 헤더구성 ------------------------------------
Row hRow = null;
// rows
int rowCnt = 0;
// 헤더 셀 병합
// === 세로 병합 (단일 컬럼) ===
sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, 0)); // 연번
sheet.addMergedRegion(new CellRangeAddress(0, 1, 1, 1)); // 사업명
sheet.addMergedRegion(new CellRangeAddress(0, 1, 2, 2)); // 입력상태
// === 가로 병합 (대분류) ===
sheet.addMergedRegion(new CellRangeAddress(0, 0, 3, 5)); // 사업내용
sheet.addMergedRegion(new CellRangeAddress(0, 0, 6, 8)); // 발주기관현황
sheet.addMergedRegion(new CellRangeAddress(0, 0, 9, 10)); // 건설사현황
// 헤더 정보 구성
for (int i = 0; i < headerNames.length; i++) {
hRow = sheet.createRow(rowCnt++);
for (int j = 0; j < headerNames[i].length; j++) {
Cell cell = headerRow.createCell(j);
cell = hRow.createCell(j);
cell.setCellStyle(headerStyle);
cell.setCellValue(headerNames[i][j]);
sheet.setColumnWidth(j, (sheet.getColumnWidth(j)) + 1000);
sheet.setColumnWidth(j, headerWidths[j]);
}
}
// ---------- 헤더구성 끝------------------------------------
for (int i = 0; i < list.size(); i++) {
EgovMap rowData = list.get(i);
Row row = sheet.createRow(i + 2);
for (int j = 0; j < headers.length; j++) {
Cell cell = row.createCell(j);
// 특정 컬럼 중앙 정렬 -----참고용------------
// if ("lvl1_rate".equals(headers[j]) ||
// "lvl2_rate".equals(headers[j]) ||
// "lvl3_rate".equals(headers[j]) ||
// "lvl2_organ_up".equals(headers[j]) ||
// "lvl3_organ_up".equals(headers[j])) {
// cell.setCellStyle(bodyStyle);
// } -----참고용------------
Object value = rowData.get(headers[j]);
// Money 타입
if ("Money".equalsIgnoreCase(columnType[j])) {
if (value instanceof Number) {
cell.setCellValue(((Number) value).doubleValue());
} else {
cell.setCellValue(0);
}
cell.setCellStyle(cellStyle1);
// Int 타입
} else if ("Int".equalsIgnoreCase(columnType[j])) {
if (value instanceof Number) {
cell.setCellValue(((Number) value).doubleValue());
} else {
cell.setCellValue(0);
}
cell.setCellStyle(cellStyle2);
// String 타입
} else {
cell.setCellValue(value == null ? "" : String.valueOf(value));
}
// 검정 테두리 적용
cell.setCellStyle(borderStyle);
}
}
//엑셀이름 한글깨짐방지
String outputFileName = new String(excelFileName.getBytes("KSC5601"), "8859_1");
response.setHeader("Set-Cookie", "fileDownload=true; path=/");
response.setHeader("Content-Disposition", String.format("attachment; filename=\""+outputFileName+"_"+ExcelMergeHeaderUtil.getTimeStampString("yyyyMMdd_HHmm")+".xlsx\""));
wb.write(response.getOutputStream());
wb.close();
} else {
createNoDataAlert(response);
}
}
public static void downExcel(List<ParamMap> list, HttpServletResponse response, String[] headers, String[] headerNames,String[] headerNames2, String[] columnType, String sheetName, String excelFileName) throws IOException {
if(ExcelMergeHeaderUtil.isNotEmpty(list)) {
// 메모리에 100개의 행을 유지합니다. 행의 수가 넘으면 디스크에 적습니다.
XSSFWorkbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet(sheetName);
Row headerRow = sheet.createRow(0);
Row headerRow2 = sheet.createRow(1);
CellStyle cellStyle1 = wb.createCellStyle(); //쉼표들어간 숫자 양식
CellStyle cellStyle2 = wb.createCellStyle(); //숫자양식
CellStyle headerStyle = wb.createCellStyle(); //숫자양식
CellStyle headerStyle2 = wb.createCellStyle();
XSSFDataFormat format = wb.createDataFormat();
cellStyle1.setDataFormat(format.getFormat("#,##0"));
cellStyle2.setDataFormat(format.getFormat("#,##0"));
cellStyle2.setAlignment(HorizontalAlignment.CENTER);
headerStyle2.setAlignment(HorizontalAlignment.CENTER);
headerStyle.setAlignment(HorizontalAlignment.CENTER);
headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
headerStyle.setFillForegroundColor((short)3);
headerStyle.setFillForegroundColor(IndexedColors.LIME.getIndex());
//로우그리기
for(int i=0; i<list.size(); i++) {
ParamMap rowData = list.get(i);
Row row = sheet.createRow(i+2);
for(int j=0; j<headers.length; j++) {
Cell cell = row.createCell(j);
if(columnType[j].equalsIgnoreCase("Int")) {
cell.setCellValue(rowData.getInt(headers[j]));
cell.setCellStyle(cellStyle2);
} else if(columnType[j].equalsIgnoreCase("String")) {
cell.setCellValue(rowData.getString(headers[j]));
} else {
cell.setCellValue(rowData.getString(headers[j]));
}
}
}
//헤더
for(int j=0; j<headerNames.length; j++) {
Cell cell = headerRow.createCell(j);
cell.setCellValue(headerNames[j]);
cell.setCellStyle(headerStyle);
sheet.autoSizeColumn(j);
sheet.setColumnWidth(j, (sheet.getColumnWidth(j)) + 1000);
}
sheet.addMergedRegion(new CellRangeAddress(0,0,0,1));
for(int j=0; j<headerNames2.length; j++) {
Cell cell = headerRow2.createCell(j);
cell.setCellValue(headerNames2[j]);
cell.setCellStyle(headerStyle2);
sheet.autoSizeColumn(j);
sheet.setColumnWidth(j, (sheet.getColumnWidth(j)) + 1000);
}
//엑셀이름 한글깨짐방지
String outputFileName = new String(excelFileName.getBytes("KSC5601"), "8859_1");
response.setHeader("Set-Cookie", "fileDownload=true; path=/");
response.setHeader("Content-Disposition", String.format("attachment; filename=\""+outputFileName+"_"+ExcelMergeHeaderUtil.getTimeStampString("yyyyMMdd_HHmm")+".xlsx\""));
wb.write(response.getOutputStream());
wb.close();
} else {
createNoDataAlert(response);
}
}
public static void downEquipStatusExcel(List<ParamMap> list, HttpServletResponse response, String[] headers, String[] headerNames,String[] headerNames2, String[] columnType, String sheetName, String excelFileName) throws IOException {
if(ExcelMergeHeaderUtil.isNotEmpty(list)) {
// 메모리에 100개의 행을 유지합니다. 행의 수가 넘으면 디스크에 적습니다.
XSSFWorkbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet(sheetName);
Row headerRow = sheet.createRow(0);
Row headerRow2 = sheet.createRow(1);
CellStyle cellStyle1 = wb.createCellStyle(); //쉼표들어간 숫자 양식
CellStyle cellStyle2 = wb.createCellStyle(); //숫자양식
CellStyle headerStyle = wb.createCellStyle(); //숫자양식
CellStyle headerStyle2 = wb.createCellStyle();
CellStyle headerStyle3 = wb.createCellStyle();
XSSFDataFormat format = wb.createDataFormat();
cellStyle1.setDataFormat(format.getFormat("#,##0"));
cellStyle2.setDataFormat(format.getFormat("#,##0"));
cellStyle2.setAlignment(HorizontalAlignment.CENTER);
headerStyle2.setBorderTop(BorderStyle.THIN);
headerStyle2.setBorderBottom(BorderStyle.THIN);
headerStyle2.setBorderLeft(BorderStyle.THIN);
headerStyle2.setBorderRight(BorderStyle.THIN);
headerStyle2.setAlignment(HorizontalAlignment.CENTER);
headerStyle2.setFillPattern(FillPatternType.SOLID_FOREGROUND);
headerStyle2.setFillForegroundColor((short)3);
headerStyle2.setFillForegroundColor(IndexedColors.LIME.getIndex());
headerStyle.setAlignment(HorizontalAlignment.CENTER);
headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
headerStyle.setFillForegroundColor((short)3);
headerStyle.setFillForegroundColor(IndexedColors.LIME.getIndex());
headerStyle3.setBorderTop(BorderStyle.THIN);
headerStyle3.setBorderBottom(BorderStyle.THIN);
headerStyle3.setBorderLeft(BorderStyle.THIN);
headerStyle3.setBorderRight(BorderStyle.THIN);
headerStyle3.setAlignment(HorizontalAlignment.CENTER);
headerStyle3.setFillPattern(FillPatternType.SOLID_FOREGROUND);
headerStyle3.setFillForegroundColor((short)3);
headerStyle3.setFillForegroundColor(IndexedColors.LIME.getIndex());
//로우그리기
for(int i=0; i<list.size(); i++) {
ParamMap rowData = list.get(i);
Row row = sheet.createRow(i+2);
for(int j=0; j<headers.length; j++) {
Cell cell = row.createCell(j);
if(columnType[j].equalsIgnoreCase("Int")) {
cell.setCellValue(rowData.getInt(headers[j]));
cell.setCellStyle(cellStyle2);
} else if(columnType[j].equalsIgnoreCase("String")) {
cell.setCellValue(rowData.getString(headers[j]));
} else {
cell.setCellValue(rowData.getString(headers[j]));
}
}
}
//헤더
for(int j=0; j<headerNames.length; j++) {
Cell cell = headerRow.createCell(j);
cell.setCellValue(headerNames[j]);
cell.setCellStyle(headerStyle3);
sheet.autoSizeColumn(j);
sheet.setColumnWidth(j, (sheet.getColumnWidth(j)) + 1000);
}
sheet.addMergedRegion(new CellRangeAddress(0,0,0,4));
sheet.addMergedRegion(new CellRangeAddress(0,0,5,10));
sheet.addMergedRegion(new CellRangeAddress(0,0,11,16));
sheet.addMergedRegion(new CellRangeAddress(0,0,17,22));
sheet.addMergedRegion(new CellRangeAddress(0,0,23,28));
sheet.addMergedRegion(new CellRangeAddress(0,0,29,31));
for(int j=0; j<headerNames2.length; j++) {
Cell cell = headerRow2.createCell(j);
cell.setCellValue(headerNames2[j]);
cell.setCellStyle(headerStyle2);
sheet.autoSizeColumn(j);
sheet.setColumnWidth(j, (sheet.getColumnWidth(j)) + 1000);
}
//엑셀이름 한글깨짐방지
String outputFileName = new String(excelFileName.getBytes("KSC5601"), "8859_1");
response.setHeader("Set-Cookie", "fileDownload=true; path=/");
response.setHeader("Content-Disposition", String.format("attachment; filename=\""+outputFileName+"_"+ExcelMergeHeaderUtil.getTimeStampString("yyyyMMdd_HHmm")+".xlsx\""));
wb.write(response.getOutputStream());
wb.close();
} else {
createNoDataAlert(response);
}
}
private static void createNoDataAlert(HttpServletResponse response) throws IOException {
response.setHeader("Content-Type", "text/html; charset=UTF-8");
PrintWriter out = response.getWriter();
out.write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">");
out.write("<html lang=\"ko\">");
out.write("<head>");
out.write("<script type=\"text/javascript\">");
out.write("alert('데이터가 없습니다.');");
out.write("history.back(-1);");
out.write("</script>");
out.write("</head>");
out.write("</html>");
out.flush();
out.close();
}
public static void setDisposition(String filename, HttpServletRequest request, HttpServletResponse response) throws IOException {
String browser = getBrowser(request);
String dispositionPrefix = "attachment; filename=";
String encodedFilename = null;
if (browser.equals("MSIE")) {
encodedFilename = URLEncoder.encode(filename, "UTF-8").replaceAll("\\+", "%20");
} else if (browser.equals("Trident")) { // IE11 문자열 깨짐 방지
encodedFilename = URLEncoder.encode(filename, "UTF-8").replaceAll("\\+", "%20");
} else if (browser.equals("Firefox")) {
encodedFilename = "\"" + new String(filename.getBytes("UTF-8"), "8859_1") + "\"";
} else if (browser.equals("Opera")) {
encodedFilename = "\"" + new String(filename.getBytes("UTF-8"), "8859_1") + "\"";
} else if (browser.equals("Chrome")) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < filename.length(); i++) {
char c = filename.charAt(i);
if(c==','){
sb.append(URLEncoder.encode("", "UTF-8"));
} else if (c > '~') {
sb.append(URLEncoder.encode("" + c, "UTF-8"));
} else {
sb.append(c);
}
}
encodedFilename = sb.toString();
} else {
throw new IOException("Not supported browser");
}
response.setHeader("Content-Disposition", dispositionPrefix + encodedFilename);
if ("Opera".equals(browser)) {
response.setContentType("application/octet-stream;charset=UTF-8");
}
if(filename.contains("zip")){
response.setContentType("application/zip");
}
}
private static String getBrowser(HttpServletRequest request) {
String header = request.getHeader("User-Agent");
if (header.indexOf("MSIE") > -1) {
return "MSIE";
} else if (header.indexOf("Trident") > -1) { // IE11 문자열 깨짐 방지
return "Trident";
} else if (header.indexOf("Chrome") > -1) {
return "Chrome";
} else if (header.indexOf("Opera") > -1) {
return "Opera";
}
return "Firefox";
}
public static String LocalDateTimeToStringDate(LocalDateTime localDateTime) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String formattedDate = localDateTime.toLocalDate().format(formatter);
return formattedDate;
}
}

View File

@ -308,6 +308,31 @@
str = String(str); str = String(str);
return str.replace(/^\s+|\s+$/g, ''); return str.replace(/^\s+|\s+$/g, '');
} }
// 엑셀 다운로드
function clickExcelDownload(){
const params = new URLSearchParams();
params.append("constTag", trim($('#const-tag').val()));
params.append("constName", trim($('#const-name').val()));
params.append("constStartDate", trim($('#const-start-date').val()));
params.append("constEndDate", trim($('#const-end-date').val()));
params.append("constStateCode", trim($('#const-state-code').val()));
params.append("projectStateCode", trim($('#project-state-code').val()));
params.append("constCompanyName", trim($('#company-dept').val()));
params.append("constCompanyAdmin", trim($('#company-admin').val()));
params.append("constCompanyTel", trim($('#company-tel').val()));
params.append("excelDownload", "Y");
// 페이지 정보
const pagingEle = document.getElementById('paging');
params.append("nPage", pagingEle.getAttribute("data-npage"));
params.append("nCount", pagingEle.getAttribute("data-ncount"));
// AJAX가 아닌 직접 다운로드 요청
window.location.href = "/admins/drilling/inquiry/excel.do?" + params.toString();
$('#excelDownload').val("");
}
</script><style> </script><style>
.drilling .page-content-inner { .drilling .page-content-inner {
padding: 30px 0; padding: 30px 0;
@ -402,26 +427,23 @@ li {
color: red; color: red;
} }
#const-state-code {
width: 180px;
height: 24px;
}
#project-state-code {
width: 160px;
height: 24px;
}
.drilling .page-content-inner{ .drilling .page-content-inner{
padding: 0; padding: 0;
} }
.drilling input, .drilling textarea, .drilling select {
border: 1px solid #d1d1d1;
font-size: 14px;
line-height: 14px;
padding: 6px 14px;
resize: none;
}
</style> </style>
</head> </head>
<body> <body>
<form id="searchForm" name="searchForm" method="post"> <form id="searchForm" name="searchForm" method="post">
<input type="hidden" id="pageIndex" name="pageIndex" value="${params.pageIndex}" /> <input type="hidden" id="pageIndex" name="pageIndex" value="${params.pageIndex}" />
<input type="hidden" id="cls" name="cls" value="2" /> <input type="hidden" id="cls" name="cls" value="2" />
<input type="hidden" id="excelDownload" name="excelDownload" value="" >
<!-- 페이지 컨테이너 시작 --> <!-- 페이지 컨테이너 시작 -->
<section class="drilling-page-container"> <section class="drilling-page-container">
<input id="PROJECT_NAME" name="PROJECT_NAME" maxlength="2000" type="hidden" value="" valid="notnull" validNm="사업명" /> <input id="PROJECT_NAME" name="PROJECT_NAME" maxlength="2000" type="hidden" value="" valid="notnull" validNm="사업명" />
@ -433,49 +455,51 @@ li {
<!-- 내용 시작 --> <!-- 내용 시작 -->
<div class="content-wrapper"> <div class="content-wrapper">
<div class="content1"> <div class="content1">
<div class="page-top-search"> <div class="page-top-search clearfix" style="display:flex">
<form class="form-inline"> <div class=""><label class="input-label-display">검색</label></div>
<label class="input-label-display">검색</label> <div class="col col-sm-11">
<input type="hidden" id="const-tag" name="const-tag" value="C" > <div class="form-inline">
<input type="search" id="const-name" name="const-name" class="input" placeholder="프로젝트명" title="" value=""> <input type="hidden" id="const-tag" name="const-tag" value="C" >
<div id="suggestionList"></div> <input type="search" id="const-name" name="const-name" class="input" placeholder="프로젝트명" title="" value="">
<input type="date" id="const-start-date" name="const-start-date" > <div id="suggestionList"></div>
<span>~</span> <input type="date" id="const-start-date" name="const-start-date" >
<input type="date" id="const-end-date" name="const-end-date" > <span>~</span>
<input type="hidden" > <input type="date" id="const-end-date" name="const-end-date" >
<select id="const-state-code" name="const-state-code"> <input type="hidden" >
<option value="" selected="selected">전체</option> <select id="const-state-code" name="const-state-code">
<option value="1">타당성조사 및 계획검토</option> <option value="" selected="selected">전체</option>
<option value="2">기본설계</option> <option value="1">타당성조사 및 계획검토</option>
<option value="3">실시설계</option> <option value="2">기본설계</option>
<option value="4">시공 중</option> <option value="3">실시설계</option>
<option value="5">준공</option> <option value="4">시공 중</option>
<option value="6">유지보수</option> <option value="5">준공</option>
</select> <option value="6">유지보수</option>
<select id="project-state-code" name="project-state-code"> </select>
<option value="" selected="selected">전체</option> <select id="project-state-code" name="project-state-code">
<option value="0">미입력</option> <option value="" selected="selected">전체</option>
<option value="1">입력 중</option> <option value="0">미입력</option>
<option value="2">검수 준비 대기중</option> <option value="1">입력 중</option>
<option value="3">검수 중</option> <option value="2">검수 준비 대기중</option>
<option value="4">수정 요청</option> <option value="3">검수 중</option>
<option value="5">검수 완료</option> <option value="4">수정 요청</option>
<option value="6">등록 완료</option> <option value="5">검수 완료</option>
</select> <option value="6">등록 완료</option>
</form> </select>
<form class="form-inline-row"> </div>
<input type="text" id="company-dept" name="company-dept" class="input input-1" placeholder="담당부서,건설사명" title="" value="" style="margin-left: 0"> <div class="form-inline" style="margin-bottom: 0">
<input type="text" id="company-admin" name="company-admin" class="input input-2" placeholder="담당자" title="" value=""> <input type="text" id="company-dept" name="company-dept" class="input input-1" placeholder="담당부서,건설사명" title="" value="" >
<input type="text" id="company-tel" name="company-tel" class="input input-3" placeholder="담당 연락처" title="" value=""> <input type="text" id="company-admin" name="company-admin" class="input input-2" placeholder="담당자" title="" value="">
<button type="button" id="btn-search" class="btn btn-search"> <input type="text" id="company-tel" name="company-tel" class="input input-3" placeholder="담당 연락처" title="" value="">
<span>조회하기</span> <button type="button" id="btn-search" class="btn btn-search">
</button> <span>조회하기</span>
<%-- <button type="button" id="btn-view-on-map" class="btn btn-view-on-map"> </button>
<span>지도보기</span> </div>
</button>--%> </div>
</form> </div>
<div class="table-info-group">
<span>Total: <span id="count">-</span>건</span>
<span class="pull-right"><img src="${pageContext.request.contextPath}/images/admins/excel.gif" style="cursor:hand" onClick="javascript:clickExcelDownload()"></span>
</div> </div>
<div class="table-info-group">Total: <span id="count">-</span>건</div>
<div class="table-wrap"> <div class="table-wrap">
<table> <table>
<colgroup> <colgroup>

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB