使用C#编写到Excel [英] Writing to Excel using C#

查看:204
本文介绍了使用C#编写到Excel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基本的WinForms应用程序,并希望能够在此应用到Excel电子表格写入数据。到目前为止,我有以下代码:

I have a basic WinForms application and want to be able to write data from this application to an Excel spreadsheet. So far I have the following code:

Microsoft.Office.Interop.Excel.Application excelapp = new Microsoft.Office.Interop.Excel.Application();
excelapp.Visible = true;

_Workbook workbook = (_Workbook)(excelapp.Workbooks.Add(Type.Missing));
_Worksheet worksheet = (_Worksheet)workbook.ActiveSheet;

worksheet.Cells[1, 1] = "Name";
worksheet.Cells[1, 2] = "Bid";

worksheet.Cells[2, 1] = txbName.Text;
worksheet.Cells[2, 2] = txbResult.Text;

excelapp.UserControl = true;

现在我想要做的是能够做的是写一个已创建的Excel文件,因此追加了。我也希望它做的这一切都在幕后,使点击一个按钮的数据被写入到电子表格并保存无需用户进行任何交互。虽然只是将数据添加到文件中未覆盖它。

Now what I want to do be able to do is write to an Excel file that has already been created, thus appending it. I also want it to do this all behind the scenes so that on a button click the data is written to the spreadsheet and saved without any interaction from the user. Whilst just adding data to the file NOT overwriting it.

推荐答案

要打开现有的工作簿从

_Workbook workbook = (_Workbook)(excelapp.Workbooks.Add(Type.Missing));

_Workbook workbook  = (_Workbook)(excelapp.Workbooks.Open(@"C:\Path\To\Your\WorkBook\ExcelWorkBook.Xlsm"));



然后保存它,你会简单地调用打开的工作簿的保存方法:

Then to save it you would simply call the Save method of the open workbook:

workbook.Save();

如果您不希望用户看到任何是怎么回事,并拥有这一切在跑背景你也应该改变你的代码行:

If you don't want the user to see anything that is going on and have it all run in the background you should also change your line of code:

excelapp.Visible = true;

excelapp.Visible = false;



你的问题的唯一部分,我下架不就是你的语句虽然只是将数据添加到文件中未覆盖它。如果你将数据添加到文件中并保存文件时,它会覆盖。你想新的工作簿保存为不同的文件?因此,有2个文件?

The only part of your question I don't under stand is you statement Whilst just adding data to the file NOT overwriting it. If you add data to a file and save that file it will overwrite. Did you want to save the new workbook as a different file? Thus having 2 files?

注意:这些要求任何第三方软件超越了互操作已经在使用,这些都是建立在功能上的互操作。这意味着你将不必下载任何东西,或增加您的项目中的任何额外的依赖。

NOTE: These do not require any third party software beyond the Interop you are already using, these are all built in function to the Interop. This mean you won't have to download anything or add any extra dependencies on your project.

这篇关于使用C#编写到Excel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆