如何使用C#将数据插入Excel表? [英] how to insert data into excel sheet using C#?
本文介绍了如何使用C#将数据插入Excel表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想创建新的excel表,并从数组中插入数据。我使用以下代码创建,现在我要插入数据。
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.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();
}
}
推荐答案
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);
}
}
这篇关于如何使用C#将数据插入Excel表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文