ps:后续我又发现写入图片也存在类似的问题,但没有得到好的解决办法,只能将图片写入到不同的行中(小菜鸡一只,希望如果有懂的大佬指点一手)
/**] * 向excel中插入表格 * @param wb Excel工作簿对象 * @param listSheet List<List<String>> 里面的list存储一列的数据,外面的list顺序存储列 * @param item 表头数据 * @param col1 指定起始的单元格列索引 * @param row1 指定起始的单元格行索引 * @param sheetIndex 需要插入表格的sheet序列 */ public static void createTableInExcel( XSSFWorkbook wb ,List<List<String>>listSheet,List<String> item, short col1, int row1, int sheetIndex){ short col2 = (short)( col1 + item.size()); XSSFCellStyle cellStyle = wb.createCellStyle(); //表格设置边框 cellStyle.setBorderBottom(BorderStyle.THIN); cellStyle.setBorderLeft(BorderStyle.THIN); cellStyle.setBorderRight(BorderStyle.THIN); cellStyle.setBorderTop(BorderStyle.THIN); //表格内容居中 cellStyle.setAlignment(HorizontalAlignment.CENTER); //单元格自动换行 cellStyle.setWrapText(true); XSSFFont font = wb.createFont(); font.setFontHeightInPoints((short) 11); cellStyle.setFont(font); XSSFSheet sheet = wb.getSheetAt(sheetIndex); XSSFRow row; if(sheet.getRow(row1)==null){ row = sheet.createRow(row1); }else { row = sheet.getRow(row1); } XSSFCell cell; //插入表头 for (int i = col1 ; i < col2; i++) { cell = row.createCell(i); cell.setCellValue(item.get(i-col1)); cell.setCellStyle(cellStyle); sheet.setColumnWidth(i,5400); } sheet.setColumnWidth(col1+1,5000);//5376 sheet.setColumnWidth(col1,4000);//5376 //插入数据 for (int i = 0; i < listSheet.get(0).size(); i++) { if(sheet.getRow(row1+1+i)==null){ row = sheet.createRow(row1+1+i); }else { row = sheet.getRow(row1+1+i); } for (int j = col1; j < col2; j++) { cell = row.createCell(j); if (listSheet.get(j - col1).get(i) == null) { listSheet.get(j - col1).set(i, " "); } cell.setCellValue(listSheet.get(j-col1).get(i)); cell.setCellStyle(cellStyle); } } }