main
黄海 2 years ago
parent ec9a3cad0b
commit eb1f30e649

@ -9,7 +9,6 @@ import com.dsideal.QingLong.Interceptor.IsLoginInterface;
import com.dsideal.QingLong.Interceptor.IsNumericInterface;
import com.dsideal.QingLong.LoginPerson.Model.LoginPersonModel;
import com.dsideal.QingLong.Util.CommonUtil;
import com.dsideal.QingLong.Collect.Util.ExcelUtil;
import com.dsideal.QingLong.Util.SessionKit;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
@ -275,8 +274,8 @@ public class CollectController extends Controller {
if (StrKit.isBlank(cell.getStringCellValue())) {
cell = wb.getSheetAt(i).getRow(start_row).getCell(colIdx);
}
ExcelUtil.addStar(wb, cell);
ExcelUtil.addComment(wb, cell, "此单元格内容必须输入!");
cm.addStar(wb, cell);
cm.addComment(wb, cell, "此单元格内容必须输入!");
}
colIdx++;
}
@ -290,7 +289,7 @@ public class CollectController extends Controller {
for (Record record : list) {
String options = record.getStr("options");
if (!StrKit.isBlank(options)) {
ExcelUtil.addValidation(wb, i, options, data_start_row, data_start_row + 20000, colIdx, colIdx);//范围
cm.addValidation(wb, i, options, data_start_row, data_start_row + 20000, colIdx, colIdx);//范围
}
colIdx++;
}
@ -387,12 +386,12 @@ public class CollectController extends Controller {
//Sheet表
XSSFSheet sheet = wb.getSheetAt(i);
//移除所有批注
ExcelUtil.RemoveAllComment(sheet);
cm.RemoveAllComment(sheet);
//数据起始行
Record r = cm.getSheetConfig(upload_excel_filename, i);
int data_start_row = r.getInt("data_start_row");
//恢复背景色
ExcelUtil.resetStyle(wb, sheet, data_start_row);
cm.resetStyle(wb, sheet, data_start_row);
//数据有效行数
int lastRowNum = sheet.getLastRowNum();
@ -408,9 +407,9 @@ public class CollectController extends Controller {
// 非空项目未填写
for (int j = data_start_row; j <= lastRowNum; j++) {//行
XSSFCell cell = sheet.getRow(j).getCell(excel_column_idx);
if (StrKit.isBlank(ExcelUtil.getValue(cell).toString())) {
ExcelUtil.addComment(wb, cell, "此处不能为空!");
ExcelUtil.fillColor(wb, cell, IndexedColors.YELLOW.getIndex());
if (StrKit.isBlank(cm.getValue(cell).toString())) {
cm.addComment(wb, cell, "此处不能为空!");
cm.fillColor(wb, cell, IndexedColors.YELLOW.getIndex());
flag = false;
}
}
@ -419,11 +418,11 @@ public class CollectController extends Controller {
if (!StrKit.isBlank(options)) {
for (int j = data_start_row; j <= lastRowNum; j++) {//行
XSSFCell cell = sheet.getRow(j).getCell(excel_column_idx);
String value = ExcelUtil.getValue(cell).toString();
String value = cm.getValue(cell).toString();
if (StrKit.isBlank(value)) value = "&*^&Y&*(&*(&*()*(";
if (options.indexOf(value) < 0) {
ExcelUtil.addComment(wb, cell, "未从指定范围内选择有效值!");
ExcelUtil.fillColor(wb, cell, IndexedColors.YELLOW.getIndex());
cm.addComment(wb, cell, "未从指定范围内选择有效值!");
cm.fillColor(wb, cell, IndexedColors.YELLOW.getIndex());
flag = false;
}
}
@ -431,19 +430,19 @@ public class CollectController extends Controller {
// 检查数据类型是不是和规定的不兼容
for (int j = data_start_row; j <= lastRowNum; j++) {//行
XSSFCell cell = sheet.getRow(j).getCell(excel_column_idx);
Object obj = ExcelUtil.getValue(cell);
Object obj = cm.getValue(cell);
if (column_type.equals("Integer") && !CommonUtil.isInteger(obj.toString())) {//要求整数,实际不是整数
ExcelUtil.addComment(wb, cell, "要求是整数,实际数据类型不是整数!");
ExcelUtil.fillColor(wb, cell, IndexedColors.YELLOW.getIndex());
cm.addComment(wb, cell, "要求是整数,实际数据类型不是整数!");
cm.fillColor(wb, cell, IndexedColors.YELLOW.getIndex());
flag = false;
} else if (column_type.equals("Double") && !CommonUtil.isDouble(obj.toString())) {//要求是浮点数,实际不是浮点数
ExcelUtil.addComment(wb, cell, "要求是小数,实际数据类型不是小数!");
ExcelUtil.fillColor(wb, cell, IndexedColors.YELLOW.getIndex());
cm.addComment(wb, cell, "要求是小数,实际数据类型不是小数!");
cm.fillColor(wb, cell, IndexedColors.YELLOW.getIndex());
flag = false;
} else if (column_type.equals("Date") && !CommonUtil.isDate(obj.toString())) {//要求是日期,实际不是日期
ExcelUtil.addComment(wb, cell, "要求是日期格式,实际数据类型不是日期格式!");
ExcelUtil.fillColor(wb, cell, IndexedColors.YELLOW.getIndex());
cm.addComment(wb, cell, "要求是日期格式,实际数据类型不是日期格式!");
cm.fillColor(wb, cell, IndexedColors.YELLOW.getIndex());
flag = false;
}
}
@ -470,7 +469,6 @@ public class CollectController extends Controller {
wb.close();
return;
}
// 检查通过,导入数据
for (int i = 0; i < sheetCnt; i++)
cm.importData(upload_excel_filename, wb, i, bureau_id, person_id);

@ -5,18 +5,17 @@ import cn.hutool.core.io.FileUtil;
import com.dsideal.QingLong.Collect.Const.DataTypeConst;
import com.dsideal.QingLong.Util.ChineseCharacterUtil;
import com.dsideal.QingLong.Util.CommonUtil;
import com.dsideal.QingLong.Collect.Util.ExcelUtil;
import com.jfinal.kit.Kv;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.xssf.usermodel.*;
import java.io.*;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
@ -129,7 +128,7 @@ public class CollectModel {
* @param type_id 1:web_data_type 2:pg_data_type 3:excel_data_type
* @return
*/
public static List<Record> listDataTypeDict = null;
public List<Record> listDataTypeDict = null;
public String getDataType(int data_type_id, int type_id) {
if (listDataTypeDict == null) listDataTypeDict = getDataTypeDict();
@ -192,7 +191,6 @@ public class CollectModel {
Db.update(sql, table_name, DateTime.now(), job_id, sheet_index);
}
/**
*
*
@ -237,7 +235,6 @@ public class CollectModel {
return Db.findFirst(sql, job_id);
}
/**
* Sheet
*
@ -356,7 +353,7 @@ public class CollectModel {
* @param pgColumnDataType
* @return
*/
public static String convertDataType(String pgColumnDataType) {
public String convertDataType(String pgColumnDataType) {
String res = "String";
if (pgColumnDataType.startsWith("varchar")) res = "String";
else if (pgColumnDataType.startsWith("int")) res = "Integer";
@ -371,7 +368,7 @@ public class CollectModel {
* @param tableName
* @return
*/
public static boolean isTableExist(String tableName) {
public boolean isTableExist(String tableName) {
String sql = "select count(*) as c from pg_class where relname = ?";
return Db.findFirst(sql, tableName).getInt("c") == 1;
}
@ -383,7 +380,7 @@ public class CollectModel {
* @param sheet_index
* @return
*/
public static Record getSheetConfig(String upload_excel_filename, int sheet_index) {
public Record getSheetConfig(String upload_excel_filename, int sheet_index) {
String sql = "select * from t_collect_config where upload_excel_filename=? and sheet_index=?";
return Db.findFirst(sql, upload_excel_filename, sheet_index);
}
@ -394,7 +391,7 @@ public class CollectModel {
* @param upload_excel_filename
* @return
*/
public static int getSheetCount(String upload_excel_filename) {
public int getSheetCount(String upload_excel_filename) {
String sql = "select * from t_collect_config where upload_excel_filename=?";
List<Record> list = Db.find(sql, upload_excel_filename);
return list.size();
@ -407,7 +404,7 @@ public class CollectModel {
* @param sheet_index
* @return
*/
public static List<Record> getSheetMapping(String upload_excel_filename, int sheet_index) {
public List<Record> getSheetMapping(String upload_excel_filename, int sheet_index) {
String sql = "select * from t_collect_mapping where upload_excel_filename=? and sheet_index=?";
return Db.find(sql, upload_excel_filename, sheet_index);
}
@ -418,8 +415,8 @@ public class CollectModel {
*
* @throws ParseException
*/
public static void importData(String upload_excel_filename, XSSFWorkbook wb,
int sheetIdx, String bureau_id, String person_id) throws ParseException {
public void importData(String upload_excel_filename, XSSFWorkbook wb,
int sheetIdx, String bureau_id, String person_id) throws ParseException {
//读取sheet页
XSSFSheet sheet = wb.getSheetAt(sheetIdx);
//通过表名获取到它的读取起始行,终止列
@ -464,11 +461,11 @@ public class CollectModel {
String colName = _map.get(j).getStr("column_name");
//cell可能是被合并的单元格
if (ExcelUtil.isMerged(sheet, cell)) {
String value = ExcelUtil.getValue(cell).toString();
if (isMerged(sheet, cell)) {
String value = getValue(cell).toString();
if (StrKit.isBlank(value)) {
for (int k = i - 1; ; k--) {
String prev = ExcelUtil.getValue(sheet.getRow(k).getCell(j)).toString();
String prev = getValue(sheet.getRow(k).getCell(j)).toString();
if (!StrKit.isBlank(prev)) {
value = prev;
break;
@ -478,13 +475,13 @@ public class CollectModel {
writeRecord.set(colName, value);
} else {
if (colType.equals("Integer"))
writeRecord.set(colName, (int) Double.parseDouble(ExcelUtil.getValue(cell).toString()));
writeRecord.set(colName, (int) Double.parseDouble(getValue(cell).toString()));
else if (colType.equals("String"))
writeRecord.set(colName, ExcelUtil.getValue(cell).toString());
writeRecord.set(colName, getValue(cell).toString());
else if (colType.equals("Double"))
writeRecord.set(colName, Double.parseDouble(ExcelUtil.getValue(cell).toString()));
writeRecord.set(colName, Double.parseDouble(getValue(cell).toString()));
else if (colType.equals("Date")) {
String dateString = ExcelUtil.getValue(cell).toString();
String dateString = getValue(cell).toString();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = dateFormat.parse(dateString);
writeRecord.set(colName, date);
@ -498,49 +495,6 @@ public class CollectModel {
Db.batchSave(table_name, writeList, 100);
}
/**
* EXCEL+ Map.Entry<Integer, Integer>
*
* @param f1
* @param f2
* @return
* @throws IOException
*/
public List<Map.Entry<Integer, Integer>> checkYiZhi(String f1, String f2, int sheetIdx) throws IOException {
Record record = getSheetConfig(FileUtil.getName(f1), sheetIdx);
int start_row = record.getInt("start_row");
int end_row = record.getInt("end_row");
int start_column = record.getInt("start_column");
int end_column = record.getInt("end_column");
FileInputStream file1 = new FileInputStream(f1);
FileInputStream file2 = new FileInputStream(f2);
List<Map.Entry<Integer, Integer>> errList = new ArrayList<>();
Workbook wb1 = WorkbookFactory.create(file1);
Workbook wb2 = WorkbookFactory.create(file2);
Sheet sheet1 = wb1.getSheetAt(sheetIdx);
Sheet sheet2 = wb2.getSheetAt(sheetIdx);
for (int i = start_row; i <= end_row; i++) {
Row row1 = sheet1.getRow(i);
Row row2 = sheet2.getRow(i);
for (int j = start_column; j <= end_column; j++) {
Cell cell1 = row1.getCell(j);
Cell cell2 = row2.getCell(j);
if (cell1 != null && cell2 != null) {
if (!cell1.getStringCellValue().equals(cell2.getStringCellValue())) {
Map.Entry<Integer, Integer> pair = new AbstractMap.SimpleEntry<>((i + 1), (j + 1));
errList.add(pair);
}
}
}
}
file1.close();
file2.close();
return errList;
}
/**
*
*/
@ -549,7 +503,7 @@ public class CollectModel {
//读取sheet页
XSSFSheet sheet = wb.getSheetAt(sheetIdx);
//找到表头
List<Integer> _list = ExcelUtil.getHead(sheet);
List<Integer> _list = getHead(sheet);
//表名称
String sheetName = wb.getSheetName(sheetIdx);
//只允许1行或2行
@ -599,4 +553,313 @@ public class CollectModel {
kv.set("sheet_name", sheetName);//Sheet名称
return kv;
}
/**
* EXCEL+ Map.Entry<Integer, Integer>
*
* @param f1
* @param f2
* @return
* @throws IOException
*/
public List<Map.Entry<Integer, Integer>> checkYiZhi(String f1, String f2, int sheetIdx) throws IOException {
Record record = getSheetConfig(FileUtil.getName(f1), sheetIdx);
int start_row = record.getInt("start_row");
int end_row = record.getInt("end_row");
int start_column = record.getInt("start_column");
int end_column = record.getInt("end_column");
FileInputStream file1 = new FileInputStream(f1);
FileInputStream file2 = new FileInputStream(f2);
List<Map.Entry<Integer, Integer>> errList = new ArrayList<>();
Workbook wb1 = WorkbookFactory.create(file1);
Workbook wb2 = WorkbookFactory.create(file2);
Sheet sheet1 = wb1.getSheetAt(sheetIdx);
Sheet sheet2 = wb2.getSheetAt(sheetIdx);
for (int i = start_row; i <= end_row; i++) {
Row row1 = sheet1.getRow(i);
Row row2 = sheet2.getRow(i);
for (int j = start_column; j <= end_column; j++) {
Cell cell1 = row1.getCell(j);
Cell cell2 = row2.getCell(j);
if (cell1 != null && cell2 != null) {
if (!cell1.getStringCellValue().equals(cell2.getStringCellValue())) {
Map.Entry<Integer, Integer> pair = new AbstractMap.SimpleEntry<>((i + 1), (j + 1));
errList.add(pair);
}
}
}
}
file1.close();
file2.close();
return errList;
}
/**
* )
* vo
*
* @param cell
* @return
*/
public String getColor(XSSFCell cell) {
if (cell != null) {
//背景颜色
CellStyle cellStyle = cell.getCellStyle();
XSSFColor xssfColor = (XSSFColor) cellStyle.getFillForegroundColorColor();
byte[] bytes;
if (xssfColor != null) {
bytes = xssfColor.getRGB();
return String.format("#%02X%02X%02X", bytes[0], bytes[1], bytes[2]);
}
}
return "BLANK";
}
/**
* Sheet,Sheet
*
* @param sheet
* @return
*/
public List<Integer> getHead(XSSFSheet sheet) {
List<Integer> list = new ArrayList<>();
//整行都是同一种非空白颜色,视为表头
// 遍历行
for (int i = 0; i <= sheet.getLastRowNum(); i++) {
//获得行
XSSFRow row = sheet.getRow(i);
//遍历列
if (row != null) {
Map<String, Integer> _map = new HashMap<>();
for (int j = 0; j < row.getLastCellNum(); j++) {
//获取单元格
XSSFCell cell = row.getCell(j);
if (cell == null) continue;
String color = getColor(cell);
//记录背景颜色数量
if (_map.containsKey(color))
_map.put(color, _map.get(color) + 1);
else
_map.put(color, 1);
}
if (_map.size() == 1 && _map.entrySet().iterator().next().getKey().startsWith("#")) {
list.add(i + 1);
}
}
}
return list;
}
/**
* Cell(*)
*
* @param wb
* @param cell
*/
public void addStar(XSSFWorkbook wb, XSSFCell cell) {
XSSFFont fontRed = wb.createFont();//第一种字体
fontRed.setBold(true);
fontRed.setColor(IndexedColors.RED.getIndex());
fontRed.setFontHeightInPoints((short) 14);
fontRed.setFontName("黑体");
XSSFFont fontBlack = wb.createFont();//第二种字体
fontBlack.setColor(IndexedColors.BLACK.getIndex());
fontBlack.setFontName("宋体");
fontRed.setBold(true);
fontBlack.setFontHeightInPoints((short) 12);
String txt = cell.getStringCellValue();
int len = txt.length();
if (len == 0) {
System.out.println(cell.getSheet().getSheetName());
System.out.println(cell.getRowIndex() + " " + cell.getColumnIndex());
System.out.println(cell.getStringCellValue());
System.out.println("发现问题:" + txt);
System.exit(0);
}
txt += "(*)";
XSSFRichTextString richText = new XSSFRichTextString(txt);//全部文字
richText.applyFont(0, len - 1, fontBlack); // 从第0个字符到第2个字符应用font1
richText.applyFont(len, len + 3, fontRed); // 从第2个字符到第4个字符应用font2
cell.setCellValue(richText);//设置文字
}
/**
*
*
* @param wb
* @param cell
*/
public void fillColor(Workbook wb, Cell cell, short colorIdx) {
// 创建单元格样式
CellStyle style = wb.createCellStyle();
style.setAlignment(HorizontalAlignment.CENTER);
style.setVerticalAlignment(VerticalAlignment.CENTER);
style.setBorderTop(BorderStyle.THIN);
style.setBorderBottom(BorderStyle.THIN);
style.setBorderLeft(BorderStyle.THIN);
style.setBorderRight(BorderStyle.THIN);
// 创建字体样式
Font font = wb.createFont();
font.setFontName("宋体");//字体
font.setBold(true);//加粗
font.setFontHeightInPoints((short) 12);//字号
style.setFont(font);
// 设置背景颜色
style.setFillForegroundColor(colorIdx);
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
// 应用样式到单元格
cell.setCellStyle(style);
}
/**
*
*
* @param sheet
*/
public void RemoveAllComment(XSSFSheet sheet) {
// 遍历所有行和单元格,移除批注
for (Row row : sheet) {
for (Cell cell : row) {
if (cell.getCellComment() != null) {
cell.removeCellComment();
}
}
}
}
/**
* Sheet
*
* @param wb
* @param sheet
*/
public void resetStyle(XSSFWorkbook wb, XSSFSheet sheet, int dataStartRow) {
// 遍历所有行和单元格,移除批注
for (int row = dataStartRow; row <= sheet.getLastRowNum(); row++) {
for (int col = 0; col < sheet.getRow(row).getLastCellNum(); col++) {
Cell cell = sheet.getRow(row).getCell(col);
fillColor(wb, cell, IndexedColors.WHITE.getIndex());
}
}
}
/**
*
*
* @param wb
* @return
*/
public void addComment(Workbook wb, Cell cell, String str) {
Sheet sheet = cell.getSheet();
// 判断单元格上是否存在批注
if (cell.getCellComment() != null) {
// 如果存在批注,先删除
cell.removeCellComment();
}
// 创建批注
Drawing<?> drawing = sheet.createDrawingPatriarch();
CreationHelper factory = wb.getCreationHelper();
ClientAnchor anchor = factory.createClientAnchor();
anchor.setCol1(cell.getColumnIndex());
anchor.setCol2(cell.getColumnIndex() + 2);
anchor.setRow1(cell.getRow().getRowNum());
anchor.setRow2(cell.getRow().getRowNum() + 3);
Comment comment = drawing.createCellComment(anchor);
comment.setString(factory.createRichTextString(str));
// 将批注添加到单元格
cell.setCellComment(comment);
}
/**
* EXCELString[]
*
* @param workbook
* @param sheetIdx
* @param firstRow
* @param lastRow
* @param firstCol
* @param lastCol
* @return
*/
public void addValidation(Workbook workbook, int sheetIdx, String options, int firstRow, int lastRow, int firstCol, int lastCol) {
String[] optionArray = options.split(",");
Sheet sheet = workbook.getSheetAt(sheetIdx);
// 删除已有的校验
DataValidationHelper dvHelper = sheet.getDataValidationHelper();
DataValidationConstraint dvConstraint = dvHelper.createCustomConstraint("DELETE_ALL");
CellRangeAddressList addressList = new CellRangeAddressList(0, 0, 0, 0); // 设置一个范围,例如整个表格范围
DataValidation validation = dvHelper.createValidation(dvConstraint, addressList);
validation.setSuppressDropDownArrow(true);
sheet.addValidationData(validation);
// 创建数据验证对象
DataValidationHelper validationHelper = sheet.getDataValidationHelper();
DataValidationConstraint constraint = validationHelper.createExplicitListConstraint(optionArray);
addressList = new CellRangeAddressList(firstRow, lastRow, firstCol, lastCol); // 指定单元格范围
validation = validationHelper.createValidation(constraint, addressList);
// 应用数据验证到单元格
sheet.addValidationData(validation);
}
/**
* Cell
*
* @param cell
* @return
*/
public Object getValue(XSSFCell cell) {
switch (cell.getCellType()) {
case CellType.STRING:
String cellValueString = cell.getStringCellValue();
return cellValueString;
case CellType.NUMERIC:
//日期格式
if (DateUtil.isCellDateFormatted(cell)) {
Date dateValue = cell.getDateCellValue();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = sdf.format(dateValue);
return formattedDate;
}
double cellValueNumeric = cell.getNumericCellValue();
return cellValueNumeric;
case CellType.BOOLEAN:
boolean cellValueBoolean = cell.getBooleanCellValue();
return cellValueBoolean;
case CellType.BLANK:
cellValueString = cell.getStringCellValue();
return cellValueString;
// 其他类型的处理
default:
cellValueString = cell.getStringCellValue();
return cellValueString;
}
}
/**
*
*
* @param sheet
* @return
*/
public boolean isMerged(XSSFSheet sheet, XSSFCell cell) {
// 判断单元格是否被合并
for (CellRangeAddress range : sheet.getMergedRegions()) {
if (cell.getRowIndex() >= range.getFirstRow() && cell.getRowIndex() <= range.getLastRow()
&& cell.getColumnIndex() >= range.getFirstColumn() && cell.getColumnIndex() <= range.getLastColumn()) {
return true;
}
}
return false;
}
}

@ -1,281 +0,0 @@
package com.dsideal.QingLong.Collect.Util;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.xssf.usermodel.*;
import java.text.SimpleDateFormat;
import java.util.*;
import static org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted;
public class ExcelUtil {
/**
* )
* vo
*
* @param cell
* @return
*/
public static String getColor(XSSFCell cell) {
if (cell != null) {
//背景颜色
CellStyle cellStyle = cell.getCellStyle();
XSSFColor xssfColor = (XSSFColor) cellStyle.getFillForegroundColorColor();
byte[] bytes;
if (xssfColor != null) {
bytes = xssfColor.getRGB();
return String.format("#%02X%02X%02X", bytes[0], bytes[1], bytes[2]);
}
}
return "BLANK";
}
/**
* Sheet,Sheet
*
* @param sheet
* @return
*/
public static List<Integer> getHead(XSSFSheet sheet) {
List<Integer> list = new ArrayList<>();
//整行都是同一种非空白颜色,视为表头
// 遍历行
for (int i = 0; i <= sheet.getLastRowNum(); i++) {
//获得行
XSSFRow row = sheet.getRow(i);
//遍历列
if (row != null) {
Map<String, Integer> _map = new HashMap<>();
for (int j = 0; j < row.getLastCellNum(); j++) {
//获取单元格
XSSFCell cell = row.getCell(j);
if (cell == null) continue;
String color = getColor(cell);
//记录背景颜色数量
if (_map.containsKey(color))
_map.put(color, _map.get(color) + 1);
else
_map.put(color, 1);
}
if (_map.size() == 1 && _map.entrySet().iterator().next().getKey().startsWith("#")) {
list.add(i + 1);
}
}
}
return list;
}
/**
* Cell(*)
*
* @param wb
* @param cell
*/
public static void addStar(XSSFWorkbook wb, XSSFCell cell) {
XSSFFont fontRed = wb.createFont();//第一种字体
fontRed.setBold(true);
fontRed.setColor(IndexedColors.RED.getIndex());
fontRed.setFontHeightInPoints((short) 14);
fontRed.setFontName("黑体");
XSSFFont fontBlack = wb.createFont();//第二种字体
fontBlack.setColor(IndexedColors.BLACK.getIndex());
fontBlack.setFontName("宋体");
fontRed.setBold(true);
fontBlack.setFontHeightInPoints((short) 12);
String txt = cell.getStringCellValue();
int len = txt.length();
if (len == 0) {
System.out.println(cell.getSheet().getSheetName());
System.out.println(cell.getRowIndex() + " " + cell.getColumnIndex());
System.out.println(cell.getStringCellValue());
System.out.println("发现问题:" + txt);
System.exit(0);
}
txt += "(*)";
XSSFRichTextString richText = new XSSFRichTextString(txt);//全部文字
richText.applyFont(0, len - 1, fontBlack); // 从第0个字符到第2个字符应用font1
richText.applyFont(len, len + 3, fontRed); // 从第2个字符到第4个字符应用font2
cell.setCellValue(richText);//设置文字
}
/**
*
*
* @param wb
* @param cell
*/
public static void fillColor(Workbook wb, Cell cell, short colorIdx) {
// 创建单元格样式
CellStyle style = wb.createCellStyle();
style.setAlignment(HorizontalAlignment.CENTER);
style.setVerticalAlignment(VerticalAlignment.CENTER);
style.setBorderTop(BorderStyle.THIN);
style.setBorderBottom(BorderStyle.THIN);
style.setBorderLeft(BorderStyle.THIN);
style.setBorderRight(BorderStyle.THIN);
// 创建字体样式
Font font = wb.createFont();
font.setFontName("宋体");//字体
font.setBold(true);//加粗
font.setFontHeightInPoints((short) 12);//字号
style.setFont(font);
// 设置背景颜色
style.setFillForegroundColor(colorIdx);
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
// 应用样式到单元格
cell.setCellStyle(style);
}
/**
*
*
* @param sheet
*/
public static void RemoveAllComment(XSSFSheet sheet) {
// 遍历所有行和单元格,移除批注
for (Row row : sheet) {
for (Cell cell : row) {
if (cell.getCellComment() != null) {
cell.removeCellComment();
}
}
}
}
/**
* Sheet
*
* @param wb
* @param sheet
*/
public static void resetStyle(XSSFWorkbook wb, XSSFSheet sheet, int dataStartRow) {
// 遍历所有行和单元格,移除批注
for (int row = dataStartRow; row <= sheet.getLastRowNum(); row++) {
for (int col = 0; col < sheet.getRow(row).getLastCellNum(); col++) {
Cell cell = sheet.getRow(row).getCell(col);
fillColor(wb, cell, IndexedColors.WHITE.getIndex());
}
}
}
/**
*
*
* @param wb
* @return
*/
public static void addComment(Workbook wb, Cell cell, String str) {
Sheet sheet = cell.getSheet();
// 判断单元格上是否存在批注
if (cell.getCellComment() != null) {
// 如果存在批注,先删除
cell.removeCellComment();
}
// 创建批注
Drawing<?> drawing = sheet.createDrawingPatriarch();
CreationHelper factory = wb.getCreationHelper();
ClientAnchor anchor = factory.createClientAnchor();
anchor.setCol1(cell.getColumnIndex());
anchor.setCol2(cell.getColumnIndex() + 2);
anchor.setRow1(cell.getRow().getRowNum());
anchor.setRow2(cell.getRow().getRowNum() + 3);
Comment comment = drawing.createCellComment(anchor);
comment.setString(factory.createRichTextString(str));
// 将批注添加到单元格
cell.setCellComment(comment);
}
/**
* EXCELString[]
*
* @param workbook
* @param sheetIdx
* @param firstRow
* @param lastRow
* @param firstCol
* @param lastCol
* @return
*/
public static void addValidation(Workbook workbook, int sheetIdx, String options, int firstRow, int lastRow, int firstCol, int lastCol) {
String[] optionArray = options.split(",");
Sheet sheet = workbook.getSheetAt(sheetIdx);
// 删除已有的校验
DataValidationHelper dvHelper = sheet.getDataValidationHelper();
DataValidationConstraint dvConstraint = dvHelper.createCustomConstraint("DELETE_ALL");
CellRangeAddressList addressList = new CellRangeAddressList(0, 0, 0, 0); // 设置一个范围,例如整个表格范围
DataValidation validation = dvHelper.createValidation(dvConstraint, addressList);
validation.setSuppressDropDownArrow(true);
sheet.addValidationData(validation);
// 创建数据验证对象
DataValidationHelper validationHelper = sheet.getDataValidationHelper();
DataValidationConstraint constraint = validationHelper.createExplicitListConstraint(optionArray);
addressList = new CellRangeAddressList(firstRow, lastRow, firstCol, lastCol); // 指定单元格范围
validation = validationHelper.createValidation(constraint, addressList);
// 应用数据验证到单元格
sheet.addValidationData(validation);
}
/**
* Cell
*
* @param cell
* @return
*/
public static Object getValue(XSSFCell cell) {
switch (cell.getCellType()) {
case CellType.STRING:
String cellValueString = cell.getStringCellValue();
return cellValueString;
case CellType.NUMERIC:
//日期格式
if (isCellDateFormatted(cell)) {
Date dateValue = cell.getDateCellValue();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = sdf.format(dateValue);
return formattedDate;
}
double cellValueNumeric = cell.getNumericCellValue();
return cellValueNumeric;
case CellType.BOOLEAN:
boolean cellValueBoolean = cell.getBooleanCellValue();
return cellValueBoolean;
case CellType.BLANK:
cellValueString = cell.getStringCellValue();
return cellValueString;
// 其他类型的处理
default:
cellValueString = cell.getStringCellValue();
return cellValueString;
}
}
/**
*
*
* @param sheet
* @return
*/
public static boolean isMerged(XSSFSheet sheet, XSSFCell cell) {
// 判断单元格是否被合并
for (CellRangeAddress range : sheet.getMergedRegions()) {
if (cell.getRowIndex() >= range.getFirstRow() && cell.getRowIndex() <= range.getLastRow()
&& cell.getColumnIndex() >= range.getFirstColumn() && cell.getColumnIndex() <= range.getLastColumn()) {
return true;
}
}
return false;
}
}
Loading…
Cancel
Save