[使用C#将信息从列表写入Excel文件

问题描述 投票:0回答:1

在我的C#代码中,我有一个包含要写入Excel文件的数据的列表。使用Interop.Excel

我该怎么办?

c# excel interop
1个回答
0
投票

添加参考和使用

 Microsoft.Office.Interop.Excel

一包代码:

List<string> list = new List<string>();
        object missing = Type.Missing;
        Excel.Application oXL = new Excel.Application();
        oXL.Visible = false;
        Excel.Workbook oWB = oXL.Workbooks.Add(missing);
        string fileName = string.Empty;
        Excel.Worksheet oSheet = oWB.ActiveSheet as Excel.Worksheet;
        var oSheetItems = oSheet;
        if (oSheetItems != null)
        {
            oSheetItems.Name = "sheatName";
            int i = 1;

            foreach (var item in list)
            {
                //insert your object
                oSheetItems.Cells[i, 1] = item;
                oSheetItems.Cells[i, 2] = item;
                i++;
            }
        }

        fileName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)
                   + "\\ExcelName.xlsx";
        oWB.SaveAs(fileName, Excel.XlFileFormat.xlOpenXMLWorkbook,
            missing, missing, missing, missing,
            Excel.XlSaveAsAccessMode.xlNoChange,
            missing, missing, missing, missing, missing);
        oWB.Close(missing, missing, missing);
        oXL.UserControl = true;
        oXL.Quit();

如果需要更多护套:在所有代码中,每个循环都使用此代码,用以下方法更改外套:

 Excel.Worksheet oSheet2 = oWB.Sheets.Add(missing, missing, 1, missing);
                oSheetItems = oSheet2;
© www.soinside.com 2019 - 2024. All rights reserved.