将内容添加到现有excel文件 [英] Add contents to existing excel file
本文介绍了将内容添加到现有excel文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在C#应用程序的现有excel文件中添加一些数据。我已经编写了一个代码,我可以在其中创建新的excel文件,我现在可以添加数据一次,我想为下一个记录添加相同的excel文件。使用现有代码替换excel文件及其内容。你能帮助我吗?以下是我的代码。有一件事我将datagrid视图的内容添加到excel。
Hi, I want to add some data in existing excel file from C# application. I have written a code from where i can create new excel file and i can add data one time now i want to append same excel file for next records. with existing code it replaces the excel file and its contents. Can you help me? follwing is my code. One thing i am adding contents of datagrid view to excel.
int i;
string filepath = "C:\\tempExcel.xls";
Microsoft.Office.Interop.Excel.ApplicationClass excelApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
excelApp.Application.Workbooks.Add(Type.Missing);
int ColumnIndex = 0;
foreach (DataGridViewColumn col in dataGridView1.Columns)
{
ColumnIndex++;
excelApp.Cells[1, ColumnIndex] = col.HeaderText;
}
for (i = 0; i <= dataGridView1.Rows.Count - 1; i++)
{
DataGridViewRow row = dataGridView1.Rows[i];
for (int j = 0; j < row.Cells.Count; j++)
{
excelApp.Cells[i + 2, j + 1] = row.Cells[j].Value.ToString();
}
}
excelApp.ActiveWorkbook.SaveCopyAs(filepath);
excelApp.ActiveWorkbook.Saved = true;
if (excelApp.ActiveWorkbook.Saved == true)
{
MessageBox.Show("Excel file is generated!");
}
excelApp.Quit();<code></code>
推荐答案
如果我理解这个问题,你可以使用打开 [ ^ ]打开现有工作簿然后进行修改的方法。
所以代码看起来像是:
If I understood the question corerctly, you can use the Open[^] method to open an existing workbook and then make the modifications.
So the code could look something like:
Excel.Application application;
Excel.Workbook workbook;
Excel.Worksheet sheet;
application = new Excel.ApplicationClass();
workbook = xlApp.Workbooks.Open("C:\\tempExcel.xls");
sheet = (Excel.Worksheet)xlWorkBook.Worksheets.Item("Sheet 1");
...
这篇关于将内容添加到现有excel文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文