前言
Java本身不支持直接读取微软的Excel表格数据。第三方的Apache提供了一个库POI用以支持Java读写Excel表格数据。
本文提供获取单元格格背景颜色和字体颜色的部分代码。
1.导入jar
还缺什么包,自行去百度上找哈。
compile group: 'org.apache.poi', name: 'poi', version: '4.1.2'
compile group: 'org.apache.poi', name: 'poi-ooxml', version: '4.1.2'
compile group: 'org.apache.poi', name: 'poi-ooxml-schemas', version: '4.1.2'
compile group: 'org.apache.poi', name: 'poi-scratchpad', version: '4.1.2'
compile group: 'org.apache.poi', name: 'poi-excelant', version: '4.1.2'
2.创建测试Excl表
3.代码
import org.apache.poi.ss.formula.eval.ErrorEval;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.util.LocaleUtil;
import org.apache.poi.xssf.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.io.FileInputStream;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* excl
*/
@Service
public class ExcelService {
private static final Logger logger = LoggerFactory.getLogger(ExcelService.class);
public static void main(String[] args) throws Exception {
InputStream input = new FileInputStream("C:\\Users\\lenovo\\Desktop\\test.xlsx");
Map<String, List<List<ExcelCellVo>>> listMap = analyzeExcel(input);
//debug看结果
System.out.println(listMap);
}
/**
* 分析excl
*
* @param is
* @return
* @throws Exception
*/
public static Map<String, List<List<ExcelCellVo>>> analyzeExcel(InputStream is) throws Exception {
try {
Workbook wb = new XSSFWorkbook(is);
Map<String, List<List<ExcelCellVo>>> sheets = new HashMap(wb.getNumberOfSheets());//根据sheet页创建map集合
for (int sheetNum = 0; sheetNum < wb.getNumberOfSheets(); ++sheetNum) {
//读取sheet页
Sheet sheet = wb.getSheetAt(sheetNum);
if (sheet != null) {
// 当前sheet页名
String sheetName = sheet.getSheetName();
List<List<ExcelCellVo>> data = new ArrayList<>();//创建list集合
// 遍历行
for (int i = 0; i <= sheet.getLastRowNum(); i++) {
//获得行
Row row = sheet.getRow(i);
List<ExcelCellVo> colData = new ArrayList<>();//创建list集合
//遍历列
if (row != null) {
for (int j = 0; j < row.getLastCellNum(); j++) {
//获取单元格
Cell cell = row.getCell(j);
Font eFont = wb.getFontAt(cell.getCellStyle().getFontIndex());//获取字体
colData.add(getCellVo(cell, eFont));
}
data.add(colData);
}
}
sheets.put(sheetName, data);
}
}
return sheets;
} catch (Exception e) {
logger.error("analyzeExcel error : {}", e);
}
return null;
}
/**
* 获取单元格vo
*
* @param cell 单元格
* @param eFont 字体
* @return
*/
private static ExcelCellVo getCellVo(Cell cell, Font eFont) {
ExcelCellVo dto = new ExcelCellVo();//创建单元格对象
if (cell != null && eFont != null) {
//值
switch (cell.getCellType()) {
case NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", LocaleUtil.getUserLocale());
sdf.setTimeZone(LocaleUtil.getUserTimeZone());
dto.setValue(sdf.format(cell.getDateCellValue()));
} else {
DataFormatter formatter = new DataFormatter();
dto.setValue(formatter.formatCellValue(cell));
}
break;
case STRING:
dto.setValue(cell.getStringCellValue());
break;
case BOOLEAN:
dto.setValue(String.valueOf(cell.getBooleanCellValue()));
break;
case FORMULA:
dto.setValue(cell.getCellFormula());
break;
case BLANK:
dto.setValue("");
break;
case ERROR:
dto.setValue(ErrorEval.getText(cell.getErrorCellValue()));
break;
default:
dto.setValue("Unknown Cell Type: " + cell.getCellType());
}
// xlsx 07版
//背景颜色
CellStyle cellStyle = cell.getCellStyle();
XSSFColor xssfColor = (XSSFColor) cellStyle.getFillForegroundColorColor();
byte[] bytes;
if (xssfColor != null) {
bytes = xssfColor.getRGB();
dto.setBackgroundColor(String.format("#%02X%02X%02X", bytes[0], bytes[1], bytes[2]));
}
//字体颜色
XSSFFont f = (XSSFFont) eFont;获取字体
XSSFColor xssffont = f.getXSSFColor();
byte[] rgb;
if (xssffont != null) {
rgb = xssffont.getRGB(); //得到rgb的byte数组
dto.setFontColor(String.format("#%02X%02X%02X", rgb[0], rgb[1], rgb[2]));
}
}
return dto;
}
}
/**
* 单元格vo
*/
public class ExcelCellVo {
private String value = "";//值
private String backgroundColor = "";//背景色
private String fontColor = "";//文字颜色
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getBackgroundColor() {
return backgroundColor;
}
public void setBackgroundColor(String backgroundColor) {
this.backgroundColor = backgroundColor;
}
public String getFontColor() {
return fontColor;
}
public void setFontColor(String fontColor) {
this.fontColor = fontColor;
}
}
4.debug结果
得到的是RGB配色。
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家的支持。
此文章也借鉴了其他老师的代码,请多多包涵.
希望能给大家带来些许灵感。
XH:别抱怨努力的苦,那是你去看世界的路。