C#将csv转换为excel 2007

本文关键字:excel 2007 转换 csv | 更新日期: 2023-09-27 18:29:51

我需要将可以升级到300000行的报告的数据导出到excel。

为了满足高速需求,我使用这个库创建了一个csv文件。我现在唯一的问题是,列宽不适合最宽单元格的内容,它会被切割,直到我手动加宽列宽。

我想也许可以选择将我的csv文件转换为excel文件,但我无论如何都找不到解决方案!

一种选择是使用OpenXML,但至少我知道,它不适用于Excel2007。

另一种选择是使用Interop,但它也有问题。。当我尝试创建Application对象时,它抛出一个异常:

"检索CLSID为{00024500-0000-0000-C000-000000000046}的组件的COM类工厂失败,原因如下错误:80070005访问被拒绝。"(HRESULT中的异常:0x80070005(E_ACCESSDENIED))

由于安全原因,我发现的解决方案无法在我正在开发的客户端上实现。

我没有选择了。。

谢谢你的帮助!!!

C#将csv转换为excel 2007

由于@mason的建议,我最终使用了EPPlus。

谢谢!

您可以使用Microsoft.Office.Interop.Excel:

using System;
using Excel = Microsoft.Office.Interop.Excel;
namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            // input and output files
            string csv = @"c:'data'input.csv";
            string xls = @"c:'data'output.xlsx";
            // init the Appl obj
            Excel.Application xl = new Excel.Application();
            // get the worksheet
            Excel.Workbook wb = xl.Workbooks.Open(csv);
            Excel.Worksheet ws = (Excel.Worksheet)wb.Worksheets.get_Item(1);
            // select the used range
            Excel.Range used = ws.UsedRange;
            // autofit the columns
            used.EntireColumn.AutoFit();
            // save as xlsx
            wb.SaveAs(xls, 51);
            wb.Close();
            xl.Quit();
        }
    }
}

或者,您可以从powershell 访问相同的方法

自动对焦.ps1

# define input and output files
$csv = Join-Path (Get-Location) "input.csv"
$xls = Join-Path (Get-Location) "myoutput.xlsx"
# initialize the COM object
$xl = New-Object -COM "Excel.Application"
$xl.Visible = $false
# open the CSV file
$wb = $xl.workbooks.open($csv)
$ws = $wb.Worksheets.Item(1)
# tell Excel to autofit the columns to the data
$range = $ws.UsedRange
[void] $range.EntireColumn.Autofit()
# save to xlsx format and close
$wb.SaveAs($xls, 51)
$wb.close()