繁体   English   中英

Powershell 将 csv 转换为 xlsx

[英]Powershell convert csv to xlsx

我有下面的 Powershell 脚本将 Excel csv 文件转换为 xlsx 工作正常。 我遇到了一个问题,当 csv 文件有像“Ä,ü,ß”这样的德语字母时,这些在 xlsx 文件中被替换为 ¼ 或类似的东西。 保存到 xlsx 时,我想使用 UTF-8 保存文件

如何使用所需的编码保存 xlsx?

### Set input and output path
$inputCSV = "test.csv"
$outputXLSX = "output.xlsx"

### Create a new Excel Workbook with one empty sheet
$excel = New-Object -ComObject excel.application 
$workbook = $excel.Workbooks.Add(1)
$worksheet = $workbook.worksheets.Item(1)

### Build the QueryTables.Add command
### QueryTables does the same as when clicking "Data » From Text" in Excel
$TxtConnector = ("TEXT;" + $inputCSV)
$Connector = $worksheet.QueryTables.add($TxtConnector,$worksheet.Range("A1"))
$query = $worksheet.QueryTables.item($Connector.name)

### Set the delimiter (, or ;) according to your regional settings
$query.TextFileOtherDelimiter = $Excel.Application.International(3)

### Set the format to delimited and text for every column
### A trick to create an array of 2s is used with the preceding comma
$query.TextFileParseType  = 1
$query.TextFileColumnDataTypes = ,2 * $worksheet.Cells.Columns.Count
$query.AdjustColumnWidth = 1

### Execute & delete the import query
$query.Refresh()
$query.Delete()

### Save & close the Workbook as XLSX. Change the output extension for Excel 2003 overwrite
$excel.DisplayAlerts = $False
$Workbook.SaveAs($outputXLSX,51)
$excel.Quit()
    string csvFileName = @"test.csv";
    string excelFileName = @"output.xlsx";

    string worksheetsName = "TEST";

    bool firstRowIsHeader = false;

    var format = new ExcelTextFormat();
    format.Delimiter = ',';
    format.EOL = "\r";             
    //format.TextQualifier = '"';
    format.Encoding = new UTF8Encoding();
    format.DataTypes = new eDataTypes[] { eDataTypes.Number, eDataTypes.String };
    ExcelPackage.LicenseContext = LicenseContext.Commercial;

    using (ExcelPackage package = new ExcelPackage(new 
             FileInfo(excelFileName)))
    {
        ExcelWorksheet worksheet = 
             package.Workbook.Worksheets.Add(worksheetsName);
           
        worksheet.Cells["A1"].LoadFromText(new FileInfo(csvFileName), format, OfficeOpenXml.Table.TableStyles.Medium27, firstRowIsHeader);
        package.Save();
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM