在C#中链接Excel [英] Linking Excel In C#

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

问题描述

所以我正在使用Microsoft Visual Studio 2015,并且希望能够将项目链接到Excel电子表格.

So I'm working in Microsoft Visual Studio 2015 and want to be able to link the project to a Excel Spreadsheet.

我想要实现的是这个;仅仅能够创建一个程序,在其中我可以在特定单元格中使用数字,然后对其进行一些计算.例如,以单元格D4为例,然后使用该值作为均值来创建泊松分布.

What I want to achieve is this; simply be able to create a program where I can use the number in a specific cell and then do some calculations with it. As an example, take cell D4 and then create a poisson distribution using the value as the mean.

推荐答案

您需要在项目参考中添加对Microsoft.Office.Core和Microsoft.Office.Interop.Excel的引用.然后将引用添加到您的课程.

You need to add a reference to Microsoft.Office.Core and Microsoft.Office.Interop.Excel in the projects References. Then add the references to your class.

using Microsoft.Office.Interop.Excel;
using Excel = Microsoft.Office.Interop.Excel;

然后,您可以在代码中打开/创建/操作Excel工作表.网上有很多信息.

Then you can open/create/manipulate excel sheets in your code. lots of info for that on the web.

更新以发表评论-

此示例打开一个新的工作表以在完成后保存.

This example is opening a new worksheet to save when done.

Excel.Application xlApp;
Excel.Workbook myWorkBook;
Excel.Worksheet myWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.ApplicationClass();
myWorkBook = xlApp.Workbooks.Add(misValue);
myWorkSheet =  (Excel.Worksheet)myWorkBook.Worksheets.get_Item(1);

在工作表上完成一些工作

Done some work on the sheet

myWorkSheet.Cells[curXLRow, 5] = "PF";
myWorkSheet.Cells[curXLRow, 6] = "PA";

然后保存文件

string fileName = "C:\\MyFileName.xlsx";
myWorkBook.SaveAs(fileName, Excel.XlFileFormat.xlWorkbookDefault, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
myWorkBook.Close(true, misValue, misValue);
xlApp.Quit();

releaseObject(myWorkSheet);
releaseObject(myWorkBook);
releaseObject(xlApp);

希望这会有所帮助.我没有打开现有Excel文件的示例.但是请查找:

Hope this helps. I dont have an example to open an existing excel file. But look up:

xlApp.Workbooks.Open(lots of parameters...);

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

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