how to insert data into excel sheet using C#?

前端 未结 2 1335
無奈伤痛
無奈伤痛 2021-01-14 14:24

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.Applic         


        
相关标签:
2条回答
  • 2021-01-14 15:03

    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:

    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);
    
    0 讨论(0)
  • 2021-01-14 15:24
    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);
                }
    
            }
    
    0 讨论(0)
提交回复
热议问题