下载模板在生成excel时,sheet1某单元格设置下拉框,动态获取sheet2生成的动态数据

@RequestMapping("/downloadFile")
@ResponseBody
public void download(String fileName, HttpServletResponse response, HttpServletRequest request) {
try {
if (!FileUtils.isValidFilename(fileName)) {
throw new Exception(StringUtils.format(“文件名称({})非法,不允许下载。 “, fileName));
}
String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf(”_”) + 1);
String filePath = RuoYiConfig.getDownloadPath() + fileName;
String path = ResourceUtils.getURL(“classpath:”).getPath()+"/download/" + fileName;

            String url="jdbc:mysql://111.204.160.119:3306/smartcampus_test?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8&allowMultiQueries=true";
            String username="jyd_dev";
            String password="dev123456";

            //创建模板
            Workbook wb = new HSSFWorkbook();
            Sheet sheet = wb.createSheet("导入模板");
            //文本格式
            HSSFCellStyle cellStyle = (HSSFCellStyle) wb.createCellStyle(); 
            HSSFDataFormat format1 = (HSSFDataFormat) wb.createDataFormat(); 
            cellStyle.setDataFormat(format1.getFormat("@"));
            //第一行
            Row row = sheet.createRow(0);
            CellStyle style = CatalogExcelUtil.getHeadStyle(wb);

            CatalogExcelUtil.initCell(row.createCell(0), style, "一卡通号");
            CatalogExcelUtil.initCell(row.createCell(1), style, "姓名");
            CatalogExcelUtil.initCell(row.createCell(2), style, "证件号");
           // CatalogExcelUtil.initCell(row.createCell(1), style, "=VLOOKUP(C2,dept!A:B,2,FALSE)");
            CatalogExcelUtil.initCell(row.createCell(3), style, "性别");
            CatalogExcelUtil.initCell(row.createCell(4), style, "手机号");
            CatalogExcelUtil.initCell(row.createCell(5), style, "职务");
            CatalogExcelUtil.initCell(row.createCell(6), style, "部门");    
            
           //行高
        	row.setHeight((short)400);
        	// 字体 字号 字体颜色
            HSSFFont f  = (HSSFFont)wb.createFont();
            f.setFontHeightInPoints((short) 12); 
            f.setFontName("宋体");
            f.setColor(IndexedColors.WHITE.getIndex());
            
          //获取单元格
            Cell  cell0=row.getCell(0);
            Cell  cell1=row.getCell(1);
            Cell  cell2=row.getCell(2);
            Cell  cell3=row.getCell(3);
            Cell  cell4=row.getCell(4);
            Cell  cell5=row.getCell(5);
            Cell  cell6=row.getCell(6);
           
            cell0.getCellStyle().setFont(f);
            cell1.getCellStyle().setFont(f);
            cell2.getCellStyle().setFont(f);
            cell3.getCellStyle().setFont(f);
            cell4.getCellStyle().setFont(f);
            cell5.getCellStyle().setFont(f);
            cell6.getCellStyle().setFont(f);
            sheet.setDefaultColumnWidth((short)15);
            //获取部门id和部门名称
            List list = deptService.selectDeptId();
            //list转数组
            String[] strings = new String[list.size()];
            String[] array = new String[list.size()];
            //list.toArray(strings);
           
            for (int i = 0; i < list.size(); i++) {
            	 //部门id
            	 strings[i]=String.valueOf(list.get(i).getDeptId());
            	 //部门名称
            	 array[i]=list.get(i).getDeptName();
			}
                // 第3列的第1行到第301行单元格部门下拉 ,可替换为从数据库的部门表数据,
                // dept 为隐藏的sheet的别名,1为这个sheet的索引 ,考虑到有多个列绑定下拉列表
               
            wb= dropDownList2003(wb, sheet, strings, 1, 300, 6, 6, "dept", 1);
          
          //设置某列 下标 单元格格式为"文本"
        	sheet.setDefaultColumnStyle(0, cellStyle);
        	sheet.setDefaultColumnStyle(4, cellStyle);
        	
        	
            //  生成sheet3
            Sheet sheet3 =wb.createSheet("部门信息参照表");
                sheet3.setDefaultColumnWidth((short)25);
              //获取数据库连接 
                Class.forName("com.mysql.cj.jdbc.Driver");
    			  // 连接数据库
    	        Connection con = (Connection) DriverManager.getConnection(url, username, password);
    	        Statement st = (Statement) con.createStatement();
	            //执行查询 sql语句,进行查询数据
	            String sql = "Select d.dept_id,d.dept_name From sys_dept d";
	            ResultSet rs = st.executeQuery(sql); 
              
                 // 设置表头信息(写入Excel左上角是从(0,0)开始的)
                 Row row3 = sheet3.createRow(0);
                 ResultSetMetaData rsmd = rs.getMetaData();
                 int colnum = rsmd.getColumnCount();
                 for (int i = 1; i <= colnum; i++) {

// String name = rsmd.getColumnName(i);
String name=null;
// 单元格
Cell cel3 = row3.createCell(i - 1);
// 写入数据
if(i等于等于1){
name=“部门ID”;
}else if(i==2){
name=“部门名称”;
}
cel3.setCellValue(name);
}
// 设置表格信息
int idx = 1;
while (rs.next()) {

                     Row row1 = sheet3.createRow(idx++);
                     for (int i = 1; i <= colnum; i++) {
                         String str = rs.getString(i);
                         // 单元格
                         Cell cell = row1.createCell(i - 1);
                         // 写入数据
                         cell.setCellValue(str);
                     }
                 }
                 
                 // 保存
                 con.close();
                
                    wb.write(new FileOutputStream(path));
	                 
    	            response.setCharacterEncoding("utf-8");
    	            response.setContentType("multipart/form-data");
    	            response.setHeader("Content-Disposition",
    	                    "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, realFileName));
    	            FileUtils.writeBytes(path, response.getOutputStream());
                
               
        } catch (Exception e) {
            //log.error("下载文件失败", e);
        }
    }

/**
* @param wb HSSFWorkbook对象
* @param realSheet 需要操作的sheet对象
* @param datas 下拉的列表数据
* @param startRow 开始行
* @param endRow 结束行
* @param startCol 开始列
* @param endCol 结束列
* @param hiddenSheetName 隐藏的sheet名
* @param hiddenSheetIndex 隐藏的sheet索引
* @return
* @throws Exception
*/
public static HSSFWorkbook dropDownList2003(Workbook wb, Sheet realSheet, String[] datas, int startRow, int endRow,
int startCol, int endCol, String hiddenSheetName, int hiddenSheetIndex)
throws Exception {

    HSSFWorkbook workbook = (HSSFWorkbook) wb;
    // 创建一个数据源sheet
    HSSFSheet hidden = workbook.createSheet(hiddenSheetName);
    // 数据源sheet页不显示
    workbook.setSheetHidden(hiddenSheetIndex, true);
    // 将下拉列表的数据放在数据源sheet上
    HSSFRow row = null;
    HSSFCell cell = null;
    for (int i = 0, length = datas.length; i < length; i++) {
        row = hidden.createRow(i);
        cell = row.createCell(0);
        cell.setCellValue(datas[i]);
    }
    //2016-12-15更新,遇到问题:生成的excel下拉框还是可以手动编辑,不满足
    //HSSFName namedCell = workbook.createName();
    //namedCell.setNameName(hiddenSheetName);
    // A1 到 Adatas.length 表示第一列的第一行到datas.length行,需要与前一步生成的隐藏的数据源sheet数据位置对应
    //namedCell.setRefersToFormula(hiddenSheetName + "!$A$1:$A" + datas.length);
    // 指定下拉数据时,给定目标数据范围 hiddenSheetName!$A$1:$A5   隐藏sheet的A1到A5格的数据
    DVConstraint constraint = DVConstraint.createFormulaListConstraint(hiddenSheetName + "!$A$1:$A" + datas.length);
    CellRangeAddressList addressList = null;
    HSSFDataValidation validation = null;
    row = null;
    cell = null;
    // 单元格样式
    CellStyle style = workbook.createCellStyle();
    style.setDataFormat(HSSFDataFormat.getBuiltinFormat("0"));
    //style.setAlignment(CellStyle.ALIGN_CENTER);
    //style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
    // 循环指定单元格下拉数据
    for (int i = startRow; i <= endRow; i++) {
        row = (HSSFRow) realSheet.createRow(i);
        cell = row.createCell(startCol);
        cell.setCellStyle(style);
        addressList = new CellRangeAddressList(i, i, startCol, endCol);
        validation = new HSSFDataValidation(addressList, constraint);
        realSheet.addValidationData(validation);
    }

    return workbook;
}

public class CatalogExcelUtil {

/**
 * 创建Workbook
 * 
 * @param in
 * @return
 * @throws Exception
 */
public static Workbook createWorkBook(InputStream in) throws Exception {
    try {
        return new HSSFWorkbook(in);
    } finally {
        if (in != null) {
            in.close();
        }
    }
}

/**
 * 获取单单元格字符串值
 * 
 * @param cell
 * @return
 */
public static String getCellStringValue(Cell cell) {
    if (cell == null) {
        return "";
    }

    cell.setCellType(HSSFCell.CELL_TYPE_STRING);
    RichTextString str = cell.getRichStringCellValue();
    return str.getString();
}

/**
 * 初始化Excel单元格, 设置单元格值和样式
 * 
 * @param cell
 * @param style
 * @param value
 */
public static void initCell(Cell cell, CellStyle style, String value) {
    cell.setCellStyle(style);
    cell.setCellValue(value);
}

/**
 * 初始化Excel单元格, 设置单元格值、样式和备注
 * 
 * @param cell
 * @param style
 * @param value
 * @param comment
 */
public static void initCell(Cell cell, CellStyle style, String value, Comment comment) {
    cell.setCellStyle(style);
    cell.setCellValue(value);
    cell.setCellComment(comment);
}

/**
 * 获取Excel单元格备注
 * 
 * @param drawing
 * @param anchor
 * @param content
 * @return
 */
public static Comment getCellComment(Drawing drawing, HSSFClientAnchor anchor, String content) {
    Comment comment = drawing.createCellComment(anchor);
    comment.setString(new HSSFRichTextString(content));
    return comment;
}

/**
 * 获取Excel标题单元格样式
 * 
 * @param wb
 * @return
 */
public static CellStyle getHeadStyle(Workbook wb) {
    CellStyle style = wb.createCellStyle();
    //设置单元格背景颜色
    HSSFCellStyle style1 =(HSSFCellStyle) wb.createCellStyle();
    //设置前景色
    style1.setFillForegroundColor(IndexedColors.GREY_40_PERCENT.getIndex());
    style1.setFillPattern(FillPatternType.SOLID_FOREGROUND);
   
    style1.setLocked(true);
    return style1;
}

/**
 * 获取Excel数据单元格样式
 * 
 * @param wb
 * @return
 */
public static CellStyle getBodyStyle(Workbook wb) {
    CellStyle style = wb.createCellStyle();
   // style.setBorderTop(HSSFCellStyle.BORDER_THIN);
   // style.setBorderRight(HSSFCellStyle.BORDER_THIN);
    //style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
   // style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
    return style;
}

/**
 * 获取Excel错误单元格样式
 * 
 * @param wb
 * @return
 */
public static CellStyle getErrorStyle(Workbook wb) {
    CellStyle style = wb.createCellStyle();

    Font font = wb.createFont();
    font.setColor(HSSFColor.RED.index);

    style.setFont(font);
    return style;
}

}
效果图如下:下载模板在生成excel时,sheet1某单元格设置下拉框,动态获取sheet2生成的动态数据_第1张图片下载模板在生成excel时,sheet1某单元格设置下拉框,动态获取sheet2生成的动态数据_第2张图片

你可能感兴趣的:(Java的导入)