目录
2.2、对已经下载完毕的文件进行检查并编辑Excel文件,标识未下载完毕的文件
1、使用场景
本文章主要记录如何使用使用POI进行基本的创建Excel文件和读取Excel文件,同时如何设定Excel文件单元格的样式。
因本人在最近一段时间,因为需要下载百度公有云上的音视频、文档文件到本地;然后根据视频主键id,去关联数据库之中的记录。因为视频下载完毕后需要上传的阿里云上;需要通过唯一主键(百度视频id)、去更新上传到阿里云上的视频id。同时需要记录下载后的每个视频文件存储在计算机磁盘上路径,然后通过后端Java程序读取Excel单元格之中文件路径;然后去通过Aliyun SDK上传文件到阿里云上去。于是此处涉及到创建Excel文件,同时需要写入一下文件基本信息。
另外需要在下载完毕后,需要检查一下Excel表格之中那些文件未下载,于是需要针对未下载视频的id的单元格进行标识。如果此视频未下载,单元格背景颜色标识为红色。
2、代码实现
2.1、pom.xml 之中引入POI的jar
<!-- Excel 使用POI操作相关jar start -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.1</version>
</dependency>
2.2、使用POI创建和读取Excel文件
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.*;
import java.util.*;
/**
* @Classname CreateExcelFile
* @Description 生产Excel文件 包括(.xls 和 .xlsx)
* 此类主要两种不同类型Excel文件的传统操作方式
* @Date 2019/11/7 11:54
* @Created by jianxiapc
*/
public class ExcelXlsOrXlsxOperate {
/**
* 判断文件的sheet是否存在.
* @param excelSuffixType 文件(.xls 和 .xlsx)
* @param fileDir 文件路径
* @param sheetName 表格索引名
* @return boolean
*/
public static boolean excelSheetIsExist(String excelSuffixType,String fileDir, String sheetName){
boolean flag = false;
File file = new File(fileDir);
Workbook workbook=null;
if (file.exists()) {
//文件存在,创建workbook
try {
if(".xls".equals(excelSuffixType)){
workbook = new HSSFWorkbook(new FileInputStream(file));
}else if(".xlsx".equals(excelSuffixType)){
workbook = new XSSFWorkbook(new FileInputStream(file));
}
Sheet sheet = workbook.getSheet(sheetName);
if (sheet!=null) {
//文件存在,sheet存在
flag = true;
}
} catch (IOException e) {
e.printStackTrace();
}
}else {
//文件不存在
flag = false;
}
return flag;
}
/**
* 创建新excel(xls).
* @param excelSuffixType 文件(.xls 和 .xlsx)
* @param fileDir excel的路径
* @param sheetNames 要创建的表格索引列表
* @param titleRow excel的第一行即表格头
*/
public static void createExcelFileBySuffix(String excelSuffixType,String fileDir, List<String> sheetNames, String titleRow[]){
Workbook workbook=null;
//创建workbook
if(".xls".equals(excelSuffixType)){
workbook = new HSSFWorkbook();
}else if(".xlsx".equals(excelSuffixType)){
workbook = new XSSFWorkbook();
}
//新建文件
FileOutputStream fileOutputStream = null;
Row row = null;
try {
CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setAlignment(HorizontalAlignment.LEFT);
cellStyle.setVerticalAlignment(VerticalAlignment.BOTTOM);
//添加Worksheet(不添加sheet时生成的xls文件打开时会报错)
for(int i = 0; i<sheetNames.size(); i++){
workbook.createSheet(sheetNames.get(i));
workbook.getSheet(sheetNames.get(i)).createRow(0);
//添加表头, 创建第一行
row = workbook.getSheet(sheetNames.get(i)).createRow(0);
row.setHeight((short)(20*20));
for (short j = 0; j < titleRow.length; j++) {
Cell cell = row.createCell(j, CellType.BLANK);
cell.setCellValue(titleRow[j]);
cell.setCellStyle(cellStyle);
}
fileOutputStream = new FileOutputStream(fileDir);
workbook.write(fileOutputStream);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
if (fileOutputStream != null) {
try {
fileOutputStream.close();
workbook.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 往excel(xls)中写入(已存在的数据无法写入). *
* @param excelSuffixType 文件(.xls 和 .xlsx)
* @param fileDir 文件路径
* @param sheetName 表格索引
* @param mapList
* @throws Exception
*/
public static void writeToExcelFileBySuffix(String excelSuffixType,String fileDir, String sheetName, List<Map<String,String>> mapList) throws Exception{
//创建workbook
File file = new File(fileDir);
Workbook workbook=null;
try {
//创建workbook
if(".xls".equals(excelSuffixType)){
workbook = new HSSFWorkbook(new FileInputStream(file));
}else if(".xlsx".equals(excelSuffixType)){
workbook = new XSSFWorkbook(new FileInputStream(file));
}
}catch(FileNotFoundException e){
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
//文件流
FileOutputStream fileOutputStream = null;
Sheet sheet = workbook.getSheet(sheetName);
// 获取表格的总行数
// int rowCount = sheet.getLastRowNum() + 1; // 需要加一
//获取表头的列数
int columnCount = sheet.getRow(0).getLastCellNum();
try {
// 获得表头行对象
Row titleRow = sheet.getRow(0);
//创建单元格显示样式
CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setAlignment(HorizontalAlignment.LEFT);
cellStyle.setVerticalAlignment(VerticalAlignment.BOTTOM);
if(titleRow!=null){
for(int rowId = 0; rowId < mapList.size(); rowId++){
Map<String,String> map = mapList.get(rowId);
Row newRow=sheet.createRow(rowId+1);
newRow.setHeight((short)(20*20));//设置行高 基数为20
for (short columnIndex = 0; columnIndex < columnCount; columnIndex++) { //遍历表头
//trim()的方法是删除字符串中首尾的空格
String mapKey = titleRow.getCell(columnIndex).toString().trim();
Cell cell = newRow.createCell(columnIndex);
cell.setCellStyle(cellStyle);
cell.setCellValue(map.get(mapKey)==null ? null : map.get(mapKey).toString());
}
}
}
fileOutputStream = new FileOutputStream(fileDir);
workbook.write(fileOutputStream);
} catch (Exception e) {
throw e;
} finally {
try {
if (fileOutputStream != null) {
fileOutputStream.close();
}
workbook.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
//String excelSuffix=".xls";
//String fileDir = "d:\\workbook.xls";
String excelSuffix=".xlsx";
String fileDir = "d:\\workbook.xlsx";
List<String> sheetName = new ArrayList<>();
sheetName.add("A");
sheetName.add("B");
sheetName.add("C");
System.out.println(sheetName);
String[] title = {"id","name","password"};
createExcelFileBySuffix(excelSuffix,fileDir, sheetName, title);
List<Map<String,String>> userList1 = new ArrayList<Map<String,String>>();
Map<String,String> map=new HashMap<String,String>();
map.put("id", "111");
map.put("name", "张三");
map.put("password", "111!@#");
Map<String,String> map2=new HashMap<String,String>();
map2.put("id", "222");
map2.put("name", "李四");
map2.put("password", "222!@#");
Map<String,String> map3=new HashMap<String,String>();
map3.put("id", "33");
map3.put("name", "王五");
map3.put("password", "333!@#");
userList1.add(map);
userList1.add(map2);
userList1.add(map3);
Map<String, List<Map<String, String>>> users = new HashMap<>();
users.put("A", userList1);
List<Map<String,String>> userList2 = new ArrayList<Map<String,String>>();
Map<String,String> map4=new HashMap<String,String>();
map4.put("id", "111");
map4.put("name", "张三");
map4.put("password", "111!@#");
Map<String,String> map5=new HashMap<String,String>();
map5.put("id", "222");
map5.put("name", "李四");
map5.put("password", "222!@#");
Map<String,String> map6=new HashMap<String,String>();
map6.put("id", "33");
map6.put("name", "王五");
map6.put("password", "333!@#");
userList2.add(map4);
userList2.add(map5);
userList2.add(map6);
users.put("B", userList2);
List<Map<String,String>> userList3 = new ArrayList<Map<String,String>>();
users.put("C", userList3);
System.out.println(sheetName.size());
//删除List 集合中特定的元素
for(Iterator<String> sheeNameIterator = sheetName.iterator();sheeNameIterator.hasNext();){
String sheet = sheeNameIterator.next();
//此时删除了第三张sheet
if ( users.get(sheet).size() == 0) {
sheeNameIterator.remove();
}
}
System.out.println(sheetName.size());
createExcelFileBySuffix(excelSuffix,fileDir, sheetName, title);
for (int j = 0; j < sheetName.size(); j++) {
try {
writeToExcelFileBySuffix(excelSuffix,fileDir, sheetName.get(j), users.get(sheetName.get(j)));
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
2.2、对已经下载完毕的文件进行检查并编辑Excel文件,标识未下载完毕的文件
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.*;
public class CheckFilesIsDownloadedUtils {
/**
*
* @param excelFilePath
* @param passCheckFileMovePath
*/
public static void checkFileIsDownloadedByIdMarkExcelRowColor(String excelFilePath,String passCheckFileMovePath) throws FileNotFoundException, IOException {
Workbook wb = null;
String extName = ".xls";
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(excelFilePath);
if (".xls".equals(extName)) {
wb = new HSSFWorkbook(fis);
} else if (".xlsx".equals(extName)) {
wb = new XSSFWorkbook(fis);
} else {
// 无效后缀名称,这里之能保证excel的后缀名称,不能保证文件类型正确,不过没关系,在创建Workbook的时候会校验文件格式
throw new IllegalArgumentException("Invalid excel version");
}
// 生成一个样式
CellStyle cellStyle = wb.createCellStyle();
cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);//填充单元格
cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN); // 设置边界的类型单元格的左边框
cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
cellStyle.setFillForegroundColor(HSSFColor.RED.index); //填红色
//1、读取Excel行之中的文件id 通过id去判断文件名之中是否包含 如果包含则移动到通过检查路基下
Sheet sheet = wb.getSheetAt(0);
// 解析sheet
int rowCount = sheet.getLastRowNum()+1;
// 解析sheet 的行
for (int j = 1; j < rowCount; j++) {
HSSFRow row = (HSSFRow) sheet.getRow(j);
if (row == null || null == row.getCell(0) || null == row.getCell(1)) {
continue;
}
if (row.getFirstCellNum() < 0) {
continue;
}
String vodeId = row.getCell(0).toString();
String vodeSrcPath = row.getCell(1).toString();
//打印不存在的文件
//PrintStream ps = new PrintStream("g:/log.txt");
//System.setOut(ps);
File notfile = new File(vodeSrcPath);
String vodeName = notfile.getName();
if(!notfile.exists()) {
System.out.println("视频文件:"+vodeId+" 不存在 "+vodeName);
row.getCell(0).setCellStyle(cellStyle);
//System.out.println("内容值: "+row.getCell(0).toString());
fos = new FileOutputStream(excelFilePath);
wb.write(fos);
}else{
//2、否则没有则标记Excel行的颜色(red)为未下载的
moveFile(vodeSrcPath,passCheckFileMovePath);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
if (fos != null) {
fos.close();
}
} catch (IOException e) {
}
}
}
/**
* 移动文件
* @param srcPath
* @param endPath
*/
public static void moveFile(String srcPath,String endPath){
try{
File file=new File(srcPath); //源文件
File tmpFile = new File(endPath);//获取文件夹路径
if(!tmpFile.exists()){//判断文件夹是否创建,没有创建则创建新文件夹
tmpFile.mkdirs();
}
if (file.renameTo(new File(endPath+file.getName()))) //源文件移动至目标文件目录
{
System.out.println("File is moved successful!");//输出移动成功
}
else
{
System.out.println("File is failed to move !");//输出移动失败
}
}catch (Exception e){
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
String excelFilePath="D:\\CheckVideoFiles\\jungangP151-217-6660.xls";
String passCheckFileMovePath="d:\\CheckVideoFiles\\PassVideoFiles\\";
checkFileIsDownloadedByIdMarkExcelRowColor(excelFilePath,passCheckFileMovePath);
}
}
3、成果展现
3.1、创建Excel文件相关结果展示
3.2、比对完毕文件后是否下载标识展示
4、总结
希望通过本文章能够针对使用POI基本操作能够有一个基本的认识,并且能够结合实际工作之中能够使用。
Workbook wb=WorkbookFactory.create(new FileInputStream(file));//可以读取xls格式或xlsx格式。
使用此种方式需注意close();问题,建议使用显性创建。
现在Alibaba已经开源了一个EasyExcel,这个性能更加优越。后续文章将介绍相关使用。