我对C#知之甚少。我正在制作从用户那里获取一些输入的窗口形式,然后我想将其保存在excel文件中。像这样的http://i.stack.imgur.com/PZubD.png,抱歉,我无法上传图像,因此图像链接在上方,因为您可以看到我制作了看起来像这样的表格,我希望保存整个表格完全在excel文件中。所有设计,标签和测试框应完全位于同一位置,以便将数据保存在excel中,如http://i.stack.imgur.com/8AmMS.png下图所示。如您所见,数量和产品名称以及价格和总量已保存在所属位置。我想要这样,所有数据都存储在它们的正下方。有可能实现吗?
我可以将数据从Windows窗体保存到excel,但不能以这种确切格式保存。那就是为什么我在这里问这个。
请帮我。
有可能做。
您将需要利用Excel Interop命名空间,特别是Microsoft.Office.Interop.Excel命名空间。
文档在这里:
https://msdn.microsoft.com/zh-CN/library/office/microsoft.office.interop.excel.aspx
它提供了写入Excel文件,更新,更改等功能。
简而言之,您将为每个单元分配所需的特定文本或标签信息。
例如,您将在方法中包含以下内容:
// Put this in the namespace references sections
using Excel = Microsoft.Office.Interop.Excel;
//inside your class(es) that will be writing to Excel
Excel.Application xlApp; //instance of the Excel application
Excel._Workbook xlWB; //will become the workbook object of the Excel application
Excel._WorkSheet xlWS; //will become the worksheet object of the Excel application
object misval = System.Reflection.Missing.Value; //used to cover certain arguements for saving (as far as I gather)
public void ExcelWriter()
{
xlApp = new Excel.Application; //starts an instance of Excel
xlApp.Visible = false; //hides the application from appearing on screen
xlApp.Dialog = false; //keeps the "Save As" dialogs from appearing when it goes to save
//adds a new workbook to the Excel application and puts a new sheet in it
xlWB = (Excel._Workbook)(xlApp.Workbooks.Add("Name of Book Goes Here"));//your workbook instance
xlWS = (Excel._WorkSheet)xlWS.ActiveSheet;//your worksheet instance
//each cell is referenced along an array
//for example, cell A1 is 1,1
xlWS.Cells[1,1] = label1.Text;
xlWS.Cells[1,2] = label2.Text;
xlWS.Cells[1,3] = label3.Text;
xlWS.Cells[1,4] = label4.Text;
.....
//whatever executable code you'd like here
//formatting of cells, fonts, etc.
xlWB.SaveAs("C:\\Path\Goes\Here", misval, misval, misval,
misval, misval, misval, misval, misval,
misval, misval, misval, misval);
xlWB.Close();
xlApp.Quit();
}
但这导致了很多问题,例如:
我也要这样说:互操作性可以正确关闭应用程序而变得非常挑剔。如果在任何地方产生导致您的应用关闭或无法正确退出Excel的错误,它将使Excel实例保持运行状态。确保检查您的任务管理器,检查异常,并确保Excel在应有的状态下退出。
其他一些参考的文章:
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句