读取xls/xlsx文件获取数据并且拼接成代码

大家好,这是我的故事!😊

读取xls/xlsx文件获取数据并且拼接成代码

题意

【题目描述】

为了满足公司工作需要,维护前端需要对较多字段名进行更改。手动更新效率太低,现在代码支持,一次一个表格。

【难点】

该功能实现几乎没有难点,主要就是对xls/xlsx文件操作的jar包的版本问题,版本不一致会出现各种报错。
所需jar

java
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AutoOutCode {

    public static void main(String[] args) {
        File file = new File("C:\\Users\\Administrator\\Desktop\\1.xlsx");
        try {
            InputStream fis = new FileInputStream(file);
            //读取导入的Excel文件内容
            XSSFWorkbook xssfWorkbook = new XSSFWorkbook(fis);
            //获取第一个sheet工作薄
            Sheet sheet = xssfWorkbook.getSheetAt(0);

            //读取出来的数据放到ListMap中
            List<Map<String, Object>> mapList =
                    new ArrayList<>();
            //获取sheet的最大row下标,实际获取的行数-1
            int lastRowNum = sheet.getLastRowNum();
            if(lastRowNum > 0){
                for(Row row : sheet){
                    //跳过表头
                    if(row.getRowNum() == 0){
                        continue;
                    }
                    //判断导入的excel文件中的是否存在空
                    boolean flag = isExistNull(row);
                    if(true){
                        Map<String, Object> susMap = new HashMap<>();
                        susMap.put("id", row.getCell(0).getStringCellValue());
                        susMap.put("intro", row.getCell(1).getStringCellValue());
                        susMap.put("def", row.getCell(2).getStringCellValue());
                        row.getCell(0).getStringCellValue();
                        //System.out.println(row.getCell(0).getStringCellValue());
                        //开始格式化
                        MyFormat(susMap);
                    }else{
                        //获取当前行数
                        int currentNum = row.getRowNum() + 1;
						//return  "第" + currentNum + "行数据出错,不能为空!"
                        System.out.println("第" + currentNum +
                                "行数据出错,不能为空!");
                    }

                }
            }else{
                System.out.println("您导入的excel文件为空,请重新导入!");
				//return "您导入的excel文件为空,请重新导入!";
            }

        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    /**
     *
     * @param map
     */
    //自己格式化
    public static void MyFormat(Map map){
        if (map.get("id").toString() == null){
            return;
        }
        String Code = "";
        if (map.get("intro") != null && map.get("intro").toString().length() >= 0){
            Code += "/**" + "\n" + " * " + map.get("intro") + "\n" + " */" + "\n";
        }
        Code += "private String " + map.get("id") + " ";
        if (map.get("def") == null || map.get("def").toString().length()==0){
            Code += "= \"\";";
        }else {
            Code += "= \"" + map.get("def") + "\";";
        }
        Code+="\n";
        String UpId = null;
        char[] cs=map.get("id").toString().trim().toCharArray();
        cs[0]-=32;
        UpId = String.valueOf(cs);
        Code += "public String " + UpId + " { get { return " + map.get("id") + "; } set { " + map.get("id") + " = value; } }";
        Code+="\n";
        System.out.println(Code);
    }

    //判断导入的excel文件中row行的每个cell时候是否存在空
    public static boolean isExistNull(Row row){
        boolean flag0 = false;
        boolean flag1 = false;
        boolean flag2 = false;
        Cell cell0 = row.getCell(0);
        if(cell0 == null){
            flag0 =  false;
        }else{
            cell0.setCellType(Cell.CELL_TYPE_STRING);
            if(cell0.getStringCellValue() == null){
                flag0 =  false;
            }
        }
        Cell cell1 = row.getCell(1);
        if(cell1 == null){
            flag1 =  false;
        }else{
            cell1.setCellType(Cell.CELL_TYPE_STRING);
            if(cell1.getStringCellValue() == null){
                flag1 =  false;
            }
        }

        Cell cell2 = row.getCell(2);
        if(cell2 == null){
            flag2 =  false;
        }else{
            cell2.setCellType(Cell.CELL_TYPE_STRING);
            if(cell2.getStringCellValue() == null){
                flag2 =  false;
            }
        }
        if (flag0 || flag1 || flag2)
            return true;

        return false;


    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
这里提供一个示例代码,可以将一个文件夹中的所有xls格式文件另存为xlsx格式文件。 ```python import os import xlrd import openpyxl # 定义要处理的文件夹路径 folder_path = "path/to/folder" # 遍历文件夹中的所有文件 for filename in os.listdir(folder_path): file_path = os.path.join(folder_path, filename) # 判断文件是否为xls格式 if filename.endswith(".xls"): print(f"Converting {filename}...") # 用xlrd读取xls文件 book = xlrd.open_workbook(file_path) sheet = book.sheet_by_index(0) data = [sheet.row_values(i) for i in range(sheet.nrows)] # 新建一个xlsx文件 new_filename = filename.replace(".xls", ".xlsx") new_file_path = os.path.join(folder_path, new_filename) # 用openpyxl写入xlsx文件 wb = openpyxl.Workbook() ws = wb.active for row in data: ws.append(row) wb.save(new_file_path) print(f"{new_filename} saved.\n") ``` 说明: 1. `os.listdir()` 方法可以列出一个文件夹中所有的文件文件夹,返回一个列表。 2. `os.path.join()` 方法可以将文件夹路径和文件拼接完整的文件路径。 3. `xlrd` 是一个读取Excel文件的第三方库,可以用来读取xls格式的文件。 4. `openpyxl` 是一个写入Excel文件的第三方库,可以用来写入xlsx格式的文件。 5. 代码中用 `xlrd` 读取xls文件,将数据保存在一个二维列表 `data` 中,然后用 `openpyxl` 新建一个xlsx文件,将 `data` 中的数据写入到文件中。 6. 文件名的处理:用字符串的 `replace()` 方法将文件名中的 ".xls" 替换为 ".xlsx",得到新的文件名。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值