将Csv文件导入Excel并替换按列

时间:2016-05-25 13:14:39

标签: c# excel linq csv

您好我需要将使用LinqToCsv liibrary从linq查询结果填充的一些csv文件导入到Excel工作簿中,方法是将逗号更改为数据之间的列吗?

`//Generate CSV Files for each item in the Listview
        CsvFileDescription outpCsvFileDescription = new CsvFileDescription
        {
            SeparatorChar = ',',
            FirstLineHasColumnNames = true
        };

        for (int i = 0; i < listView.Items.Count; i++)
        {
            dynamic currentItemInLoop = listView.Items[i];
            //On est obligé de cast cette variable en String pour qu'on puisse l'utiliser dans le LinQ
            //currentItemInLoop.nameAttribute => MainWindow.xaml -> ListView x:Name="listView" -> Columns...
            String frs = (String)currentItemInLoop.Name;
            DateTime myDate = (DateTime) currentItemInLoop.TransactionDate;
            var infoEcheances = from f in db.F_ECHEANCES
                                join c in db.F_LECRITURES on f.ECH_No equals c.ECH_No
                                where
                    f.ECH_Intitule == frs &&
                    EntityFunctions.TruncateTime(f.cbModification) ==
                    EntityFunctions.TruncateTime(DatePicker.SelectedDate)
                select
                    new 
                    {
                        f.ECH_DateEch,
                        f.ECH_RefPiece,
                        f.ECH_Libelle,
                        c.LEC_Montant,
                        f.ECH_Montant
                    };

            CsvContext cc = new CsvContext();
            string myPath = @"C:\Users\DefaultAccount\Desktop\Projet Top Of Travel\FichiersCSV\";
            string filename = string.Format(frs);
            filename = Regex.Replace(filename + " " + myDate, @"[^0-9a-zA-Z]", " ");
            string finalPath = System.IO.Path.Combine(myPath, filename + ".csv");
            cc.Write(infoEcheances, finalPath, outpCsvFileDescription);`

1 个答案:

答案 0 :(得分:1)

您可以使用COM从c#直接进入Excel。

using Excel = Microsoft.Office.Interop.Excel; 

public class ExcelReports
{
    public Excel.Application excelApp;
    public Excel.Workbook excelWorkbook;
    public Excel.Worksheet excelWorksheet;
    public int row = 1;
    public int col = 1;

    public ExcelReports( String fullName )
    {
        excelApp = new Excel.Application();

        Excel.Workbook newWorkbook = excelApp.Workbooks.Add();
        excelWorkbook = excelApp.ActiveWorkbook;

        excelWorksheet = (Excel.Worksheet)excelWorkbook.Worksheets.Add();
        excelWorksheet.Cells.ClearContents();
        excelWorksheet.Cells[row, col]  = "hello";
  }

}

设置单元格的代码....从我的代码中剪切...你会改变它来输出yr数组中的每一行。它可能需要按摩才能工作。网上有很多广泛的例子。有一些优化可以使这项工作变得更快。

Excel还会导入CSV文件并允许您控制分隔符等,但此过程是手动的。