将内容添加到现有excel文件

编程入门 行业动态 更新时间:2024-10-21 15:45:02
本文介绍了将内容添加到现有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文件

本文发布于:2023-11-27 08:14:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1637238.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件   内容   excel

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!