You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Excel Script+Power Automate转换CSV至XLSX出现乱码求助

CSV转XLSX乱码问题排查(Excel Script + Power Automate)

我使用Excel Script搭配Power Automate流,实现将OneDrive某文件夹中的CSV文件自动转换为另一文件夹内XLSX文件的自动化任务。采用了微软官方提供的脚本,代码可正常运行并生成XLSX文件,但文件内容存在乱码问题。

所用脚本

/**
 * Convert incoming CSV data into a range and add it to the workbook.
 */
function main(workbook: ExcelScript.Workbook, csv: string) {
  let sheet = workbook.getWorksheet("Sheet1");

  // Remove any Windows \r characters.
  csv = csv.replace(/\r/g, "");

  // Split each line into a row.
  let rows = csv.split("\n");
  /*
   * For each row, match the comma-separated sections.
   */
  const csvMatchRegex = /(?:,|\n|^)("(?:(?:"")*[^"]*)*"|[^",\n]*|(?:\n|$))/g
  rows.forEach((value, index) => {
    if (value.length > 0) {
        let row = value.match(csvMatchRegex);
    
        // Check for blanks at the start of the row.
        if (row[0].charAt(0) === ',') {
          row.unshift("");
        }
    
        // Remove the preceding comma.
        row.forEach((cell, index) => {
          row[index] = cell.indexOf(",") === 0 ? cell.substr(1) : cell;
        });
    
        // Create a 2D array with one row.
        let data: string[][] = [];
        data.push(row);
    
        // Put the data in the worksheet.
        let range = sheet.getRangeByIndexes(index, 0, 1, data[0].length);
        range.setValues(data);
    }
  });

  // Add any formatting or table creation that you want.
}

可能的乱码原因

  • 编码不匹配:CSV文件若为UTF-8带BOM、GBK等非默认编码,Power Automate读取时未指定对应编码,导致传入脚本的csv字符串已乱码。默认情况下Power Automate读取文本文件可能采用系统编码,而非UTF-8。
  • 正则解析字符异常:脚本中的正则表达式处理包含非ASCII字符的CSV内容时,可能出现匹配错误,引发字符截断或篡改。
  • 换行符处理不完整:脚本仅移除了\r,若CSV使用其他换行格式或行尾换行符异常,可能导致行拆分错误,间接引发乱码。
  • Excel字符兼容问题:写入单元格时,部分特殊字符(如全角符号、非拉丁字符)未被正确识别,需确认Excel的字符编码支持。

验证与解决方向

  1. 检查CSV文件实际编码(用记事本打开,通过“另存为”选项查看编码)
  2. 在Power Automate的「获取文件内容」步骤中,指定编码为UTF-8(若CSV为UTF-8编码),避免读取阶段编码错误
  3. 测试简化脚本:将csv字符串输出到日志,确认传入脚本的内容是否已乱码,定位问题出在读取还是解析阶段
  4. 调整正则表达式:确保正则支持Unicode字符匹配,避免非ASCII字段解析异常

内容的提问来源于stack exchange,提问作者Leandro Abraham

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 06:47:40