如何使用C#将数据插入到excel表中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11627344/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 18:33:52  来源:igfitidea点击:

how to insert data into excel sheet using C#?

c#excel

提问by chitra

i want to create new excel sheet and insert data into it, from string array. i used the following code to create, now i want to insert data.

我想从字符串数组创建新的 Excel 工作表并将数据插入其中。我使用以下代码创建,现在我想插入数据。

    Excel.Application xlApp;
            Excel.Workbook xlWorkBook;
            Excel.Worksheet xlWorkSheet;
            object misValue = System.Reflection.Missing.Value;
            xlApp = new Excel.Application();
            //xlApp = new Excel._Application.ApplicationClass();
            xlWorkBook = xlApp.Workbooks.Add(misValue);

            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
            xlWorkSheet.Cells[1, 1] = "http://csharp.net-informations.com";

            xlWorkBook.SaveAs("csharp-Excel.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
            xlWorkBook.Close(true, misValue, misValue);
            xlApp.Quit();

            releaseObject(xlWorkSheet);
            releaseObject(xlWorkBook);
            releaseObject(xlApp);
}
    private void releaseObject(object obj)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
                obj = null;
            }
            catch (Exception ex)
            {
                obj = null;
                MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
            }
            finally
            {
                GC.Collect();
            }
        }

回答by Mutu Yolbulan

private void ExportToExcel(string fileName, DataGridView dgv) //Exports the given dataGridView to Excel with the given fileName
        {
            Excel.Application xlApp;
            Excel.Workbook xlWorkBook;
            Excel.Worksheet xlWorkSheet;
            object misValue = System.Reflection.Missing.Value;

            xlApp = new Excel.Application();
            xlWorkBook = xlApp.Workbooks.Add(misValue);
            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
            int i = 0;
            int j = 0;

            DataTable dtExcelTable = GetDataTableForExcel(dgv);

            for (i = 0; i < dtExcelTable.Columns.Count; i++)
            {
                xlWorkSheet.Cells[1, i + 1] = dtExcelTable.Columns[i].ColumnName;
            }

            for (i = 0; i < dtExcelTable.Rows.Count; i++)
            {
                for (j = 0; j < dtExcelTable.Columns.Count; j++)
                {
                    xlWorkSheet.Cells[i + 2, j + 1] = dtExcelTable.Rows[i][j];
                }
            }

            try
            {
                xlWorkBook.SaveAs(fileName + ".xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
                xlWorkBook.Close(true, misValue, misValue);
                xlApp.Quit();

                releaseObject(xlWorkSheet);
                releaseObject(xlWorkBook);
                releaseObject(xlApp);

                MessageBox.Show("Excel dosyan?z C:\" + fileName + ".xls uzant?s?nda yarat?ld?.");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Bir sorun olu?tu, tekrar deneyiniz. Hata: " + ex.Message);
            }

        }

回答by simendsjo

Calling COM methods is very slow. If you plan to insert a lot of data, I recommend you fetch the entire range you need, set all values, and add it back:

调用 COM 方法非常慢。如果您打算插入大量数据,我建议您获取所需的整个范围,设置所有值,然后将其添加回来:

var range = xlWorkSheet.get_Range[firstCell, lastCell]; // or string range
var data = (object[,])range.get_Value(XlRangeValueDataType.xlRangeValueDefault);
// Set data here. Remember it's 1 based index, and row (y component) first
range.set_Value(data);