在csv文件的所有列中添加引号

时间:2019-03-02 21:22:54

标签: excel csv batch-file

我想有一个批处理文件,它将转换我的csv格式

value1,value2,value3

进入

"value1","value2","value3"

我试图直接在Excel文件中执行相同操作(根据此答案https://stackoverflow.com/a/38728364),但是当我保存文件时,我在记事本中看到它是

"""value1""","""value2""","""value3"""

仅使用vba脚本可以工作,但使用起来不方便。 因此,现在我正在寻找一些脚本,这些脚本比打开excel,选择范围并上传VBA脚本以转换值的速度更快。我找到了powershell脚本,但在我的情况下无效。我用谷歌搜索,只找到了如何删除引号,而不是如何添加它们:D

您还有其他想法如何直接在Excel中或在批处理文件中实现吗?

1 个答案:

答案 0 :(得分:0)

您可以执行以下操作(请参见说明性的rem备注):

@echo off
rem // Read CSV file that is provided as command line argument:
for /F "usebackq delims=" %%L in ("%~1") do (
    rem // Store currently read line:
    set "LINE=%%L"
    rem /* Toggle delayed expansion to be able to write and read a variable in the same block of code
    rem    (without it reading a variable would return the value present before the whole block executes): */
    setlocal EnableDelayedExpansion
    rem /* Return the current line but enclose it within `""`
    rem    and replace every `,` by `","`;
    rem    this results in every comma -separated field to appear in between quotes: */
    echo("!LINE:,=","!"
    endlocal
)

这是基于这样一个假设,即没有字段值本身包含逗号。