如何创建简单的 Excel 2007 工作簿或简单的 Word 2007 文档中使用 Office XML 文件格式和 $ 从.net Framework 3.0 包装组件

文章翻译 文章翻译
文章编号: 931866 - 查看本文应用于的产品
展开全部 | 关闭全部

本文内容

简介

本文介绍了如何使用 Microsoft Office XML 文件格式和 $ Microsoft.net 框架 3.0 创建简单的 Microsoft Office Excel 2007 工作簿或简单的 Microsoft Office Word 2007 文档中的打包组件。

更多信息

在这篇文章中的代码示例创建一个新 Excel 工作簿或包含文字"Hello World"的新的 Word 文档而不自动化 Excel 2007 或 Word 2007。

客户端要求

  • Microsoft Visual Studio 2005 或 Microsoft Visual C# 2005
  • .NET 框架 3.0
  • .NET 框架的 visual Studio 2005 扩展 3.0
  • Excel 2007 或 Word 2007

逐步骤示例

创建基于 Windows 的应用程序

  1. 启动 Visual Studio 2005 或 Visual C# 2005年。
  2. 创建一个新的 Visual C# Windows 应用程序。
  3. 添加对 Windowsbase.dll 程序集的引用。

    注意如果 Windowsbase.dll 引用不会出现在 添加引用 对话框的 .net 选项卡上,单击 浏览 选项卡,找到是 Files\Reference 的 assemblies\Microsoft\Framework\v3.0 文件夹,然后单击 $ WindowsBase.dll
  4. 可视的 Studio 中单击在 视图 切换到代码视图菜单上的 代码
  5. Form1 类中添加下面的指令。
    	
    	using System.Xml;
    	using System.IO;
    	using System.IO.Packaging;
    
    

添加代码以创建 Excel 工作簿

  1. 可视的 Studio 中单击切换到设计视图中为窗体 视图 菜单上的 设计器
  2. 将一个 按钮 控件添加到 Windows 窗体。设置 文本创建 Excel 工作簿 按钮的属性。
  3. 双击 Button 控件生成 button1_Click 事件处理程序。
  4. 添加下面的代码示例,到 button1_Click 事件处理程序。新的事件处理程序代码应类似于下面的代码示例
    	private void button1_Click(object sender, EventArgs e)
            {
                //Create the XML documents.
                XmlDocument workbookDoc = null;
                workbookDoc = CreateExcelXML("workbook");
    
                XmlDocument worksheetDoc = null;
                worksheetDoc = CreateExcelXML("worksheet");
    
                XmlDocument sharedstringsDoc = null;
                sharedstringsDoc = CreateExcelXML("sharedstrings");
    
                //Create the Excel package.
                Package xlPackage = null;
                xlPackage = CreateExcelWorkbookPackage("HelloWorld.xlsx");
    
                //Add the parts to the Excel package.
                if (xlPackage != null)
                {
                    //Add the workbook part.
                    AddExcelPart(xlPackage, "workbook", workbookDoc);
    
                    //Add the worksheet part.
                    AddExcelPart(xlPackage, "worksheet", worksheetDoc);
    
                    //Add the sharedstrings part.
                    AddExcelPart(xlPackage, "sharedstrings", sharedstringsDoc);
    
                }
    
                //Save the changes, and then close the package.
                if (xlPackage != null)
                {
                    xlPackage.Flush();
                    xlPackage.Close();
                }
    
                MessageBox.Show("Successfully created Excel workbook");
            }
    
  5. 添加到 Form1 类下面的代码示例。此代码示例创建并插入包含 Excel 工作表的 XML 组件
    	  private XmlDocument CreateExcelXML(string partType)
            {
                switch (partType)
                {
                    case "workbook":
                        //Create a new XML document for the workbook.
                        XmlDocument workbookDoc = new XmlDocument();
    
                        //Obtain a reference to the root node, and then add
                        //the XML declaration.
                        XmlElement wbRoot = workbookDoc.DocumentElement;
                        XmlDeclaration wbxmldecl = 
    					workbookDoc.CreateXmlDeclaration
    					("1.0", "UTF-8", "yes");
                        workbookDoc.InsertBefore(wbxmldecl, wbRoot);
    
                        //Create and append the workbook node
                        //to the document.
                        XmlElement workBook = 
    					workbookDoc.CreateElement("workbook");
                        workBook.SetAttribute("xmlns",
                            "http://schemas.openxmlformats.org/" +
                            "spreadsheetml/2006/main");
                        workBook.SetAttribute("xmlns:r",
                            "http://schemas.openxmlformats.org/officeDocument/" +
                            "2006/relationships");
                        workbookDoc.AppendChild(workBook);
    
                        //Create and append the sheets node to the 
                        //workBook node.
                        XmlElement sheets = workbookDoc.CreateElement("sheets");
                        workBook.AppendChild(sheets);
    
    
                        //Create and append the sheet node to the 
                        //sheets node.
                        XmlElement sheet = workbookDoc.CreateElement("sheet");
                        sheet.SetAttribute("name", "Sheet1");
                        sheet.SetAttribute("sheetId", "1");
      sheet.SetAttribute("id",
    				"http://schemas.openxmlformats.org/" +
    				"officeDocument/2006/relationships","rId1");
                        sheets.AppendChild(sheet);
    
                        return workbookDoc;
    
                    case "worksheet":
                        //Create a new XML document for the worksheet.
                        XmlDocument worksheetDoc = new XmlDocument();
    
                        //Get a reference to the root node, and then add
                        //the XML declaration.
                        XmlElement wsRoot = worksheetDoc.DocumentElement;
                        XmlDeclaration wsxmldecl = 
                            worksheetDoc.CreateXmlDeclaration("1.0", 
    "UTF-8", "yes");
                        worksheetDoc.InsertBefore(wsxmldecl, wsRoot);
    
    
                        //Create and append the worksheet node
                        //to the document.
                        XmlElement workSheet = 
    					worksheetDoc.CreateElement("worksheet");
                        workSheet.SetAttribute("xmlns",
                            "http://schemas.openxmlformats.org/" +
                            "spreadsheetml/2006/main");
                        workSheet.SetAttribute("xmlns:r",
                            "http://schemas.openxmlformats.org/" +
                            "officeDocument/2006/relationships");
                        worksheetDoc.AppendChild(workSheet);
                                           
                        //Create and add the sheetData node.
                        XmlElement sheetData = 
    					worksheetDoc.CreateElement("sheetData");
                        workSheet.AppendChild(sheetData);
    
                        //Create and add the row node. 
                        XmlElement rNode = worksheetDoc.CreateElement("row");
                        rNode.SetAttribute("r", (1).ToString());
                        rNode.SetAttribute("spans", "1:1");
                        sheetData.AppendChild(rNode);
    
                        //Create and add the column node.
                        XmlElement cNode = worksheetDoc.CreateElement("c");
                        cNode.SetAttribute("r", "A1");
                        cNode.SetAttribute("t", "s");
                        rNode.AppendChild(cNode);
    
                        //Add the "Hello World" text to the worksheet.
                        XmlElement vNode = worksheetDoc.CreateElement("v");
                        vNode.InnerText = "0";
                        cNode.AppendChild(vNode);
    
                        return worksheetDoc;
                        
                    case "sharedstrings":
                        //Create a new XML document for the sharedStrings.
                        XmlDocument sharedStringsDoc = new XmlDocument();
    
                        //Get a reference to the root node, and then add
                        //the XML declaration.
                        XmlElement ssRoot = sharedStringsDoc.DocumentElement;
                        XmlDeclaration ssxmldecl =
                            sharedStringsDoc.CreateXmlDeclaration("1.0", 
    "UTF-8", "yes");
                        sharedStringsDoc.InsertBefore(ssxmldecl, ssRoot);
    
                        //Create and append the sst node.
                        XmlElement sstNode = 
    					sharedStringsDoc.CreateElement("sst");
                        sstNode.SetAttribute("xmlns", 
    					"http://schemas.openxmlformats.org/" +
                            "spreadsheetml/2006/main");
                        sstNode.SetAttribute("count", "1");
                        sstNode.SetAttribute("uniqueCount", "1");
                        sharedStringsDoc.AppendChild(sstNode);
    
                        //Create and append the si node.
                        XmlElement siNode = sharedStringsDoc.CreateElement("si");
                        sstNode.AppendChild(siNode);
    
                        //Create and append the t node.
                        XmlElement tNode = sharedStringsDoc.CreateElement("t");
                        tNode.InnerText = "Hello World";
                        siNode.AppendChild(tNode);
    
                        return sharedStringsDoc;   
             
                    default:
                        return null;
                }
            }
    
            private Package CreateExcelWorkbookPackage(string fileName)
            {
                //Create a new Excel workbook package on the
                //desktop of the user by using the specified name.
                string desktopDir = System.Environment.GetFolderPath(
                            Environment.SpecialFolder.DesktopDirectory);
    
                Package xlPackage = Package.Open(desktopDir + "\\" + fileName,
                        FileMode.Create, FileAccess.ReadWrite);
    
                return xlPackage;
    
            }
    
            private void AddExcelPart(Package fPackage, string part, 
    XmlDocument xDoc)
            {
                switch (part)
                { 
                    case "workbook":
                        string nsWorkbook = "application/vnd.openxmlformats-" +
                                "officedocument.spreadsheetml.sheet.main+xml";
                        string workbookRelationshipType = 
    "http://schemas.openxmlformats.org/" +                            "officeDocument/2006/relationships/" +
    "officeDocument";
                        Uri workBookUri = PackUriHelper.CreatePartUri(new 
                                Uri("xl/workbook.xml",UriKind.Relative));
    
                        //Create the workbook part.
                        PackagePart wbPart =
                                fPackage.CreatePart(workBookUri, nsWorkbook);
    
                        //Write the workbook XML to the workbook part.
                        Stream workbookStream = 
                                wbPart.GetStream(FileMode.Create, 
    					FileAccess.Write);
                        xDoc.Save(workbookStream);
    
                        //Create the relationship for the workbook part.
                        fPackage.CreateRelationship(workBookUri,
                            TargetMode.Internal,
    workbookRelationshipType,"rId1");
    
                        break;
    
                    case "worksheet":
                        string nsWorksheet = "application/vnd.openxmlformats-" +
                                "officedocument.spreadsheetml.worksheet+xml";
                        string worksheetRelationshipType = 
    				"http://schemas.openxmlformats.org/" +
                            "officeDocument/2006/relationships/worksheet";
                        Uri workSheetUri = PackUriHelper.CreatePartUri(new
                              Uri("xl/worksheets/sheet1.xml",UriKind.Relative));
    
                        //Create the workbook part.
                        PackagePart wsPart =
                                fPackage.CreatePart(workSheetUri, nsWorksheet);
    
                        //Write the workbook XML to the workbook part.
                        Stream worksheetStream =
                                  wsPart.GetStream(FileMode.Create, 
    					FileAccess.Write);
                        xDoc.Save(worksheetStream);
    
                        //Create the relationship for the workbook part.
                        Uri wsworkbookPartUri = PackUriHelper.CreatePartUri(new 
                                Uri("xl/workbook.xml",UriKind.Relative));
                        PackagePart wsworkbookPart = 
    					fPackage.GetPart(wsworkbookPartUri);
                        wsworkbookPart.CreateRelationship(workSheetUri,
                                  TargetMode.Internal, 
    worksheetRelationshipType,"rId1");
                        
                        break;
    
                    case "sharedstrings":
                        string nsSharedStrings = 
    				"application/vnd.openxmlformats-officedocument" +
                            ".spreadsheetml.sharedStrings+xml";
                        string sharedStringsRelationshipType = 
    "http://schemas.openxmlformats.org" +                            "/officeDocument/2006/relationships/sharedStrings";
                        Uri sharedStringsUri = PackUriHelper.CreatePartUri(new
                              Uri("xl/sharedStrings.xml", UriKind.Relative));
    
                        //Create the workbook part.
                        PackagePart sharedStringsPart =                          						fPackage.CreatePart(sharedStringsUri,
    nsSharedStrings);
    
                        //Write the workbook XML to the workbook part.
                        Stream sharedStringsStream =
                                sharedStringsPart.GetStream(FileMode.Create,
    FileAccess.Write);
                        xDoc.Save(sharedStringsStream);
    
                        //Create the relationship for the workbook part.
                        Uri ssworkbookPartUri = PackUriHelper.CreatePartUri(new
                                Uri("xl/workbook.xml", UriKind.Relative));
                        PackagePart ssworkbookPart = 
    					fPackage.GetPart(ssworkbookPartUri);
                        ssworkbookPart.CreateRelationship(sharedStringsUri,
                                TargetMode.Internal, 
    					sharedStringsRelationshipType,"rId2");
    
                        break;
                }
            }
    
  6. 保存项目。

添加代码以创建 Word 文档

  1. 可视的 Studio 中单击切换到设计视图中为窗体 视图 菜单上的 设计器
  2. 将另一个 按钮 控件添加到 Windows 窗体。将按钮的 Text 属性设置为 Word 文档创建
  3. 双击 Button 控件生成 button2_Click 事件处理程序。
  4. 将代码添加到 button2_Click 事件处理程序,以使它类似于下面的代码示例
    	private void button2_Click(object sender, EventArgs e)
            {
                //Create the XML for the Word document.
                XmlDocument xDoc = null;
                xDoc = CreateDocumentXML("Hello World");
    
                //Create the Word document package.
                if (xDoc != null)
                {
                    bool hResult = CreateWordDocumentPackage("HelloWorld.docx",
    			 xDoc);
    
                    if (hResult == true)
                    {
                        MessageBox.Show("Successfully created Word document");
                    }
                }
            }
            
    
  5. 添加到 Form1 类下面的代码示例。 此代码示例创建并插入 XML 组件包含在 Word 文档
    	private XmlDocument CreateDocumentXML(string docText)
            {
                string nsWordML =
                      "http://schemas.openxmlformats.org/wordprocessingml" +
                      "/2006/main";
                
                //Create a new XML document.
                XmlDocument xDoc = new XmlDocument();
    
                //Create and add the document node.
                XmlElement docNode =
                   xDoc.CreateElement("w:document", nsWordML);
                xDoc.AppendChild(docNode);
    
                //Create and add the body node to the 
                //document node.
                XmlElement bodyNode = 
                    xDoc.CreateElement("w:body", nsWordML);
                docNode.AppendChild(bodyNode);
    
                //Create and add the wp node to the docNode.
                XmlElement wpNode =
                   xDoc.CreateElement("w:p", nsWordML);
                bodyNode.AppendChild(wpNode);
    
                //Create and add the wr node to the wpNode.
                XmlElement wrNode =
                   xDoc.CreateElement("w:r", nsWordML);
                wpNode.AppendChild(wrNode);
    
                //Create and add the wt node to the wrNode.
                XmlElement wtNode =
                   (XmlElement)xDoc.CreateNode(XmlNodeType.Element,
                   "w", "t", nsWordML);
                wrNode.AppendChild(wtNode);
    
                //Add the supplied text to the wtNode.
                wtNode.InnerText = docText;
    
                return xDoc;
            }
    
           private bool CreateWordDocumentPackage(string fileName, 
    XmlDocument xDoc)
            {
                try
                {
                    string docContentType = "application/vnd.openxmlformats-" +
                            "officedocument.wordprocessingml." +
                            "document.main+xml";
                    
                    string docRelationshipType = 
    				"http://schemas.openxmlformats.org" +
                            "/officeDocument/2006/relationships/" +
                            "officeDocument";
    
                    //Create a new package file on the desktop of the user by using
                    //the supplied file name.
                    string desktopDir = System.Environment.GetFolderPath(
                            Environment.SpecialFolder.DesktopDirectory);
    
                    Package pkg = Package.Open(desktopDir + "\\" + fileName, 
                          FileMode.Create, FileAccess.ReadWrite);
                    
                                
                    //Create a Uri for the document part.
                    Uri docPartURI = PackUriHelper.CreatePartUri(
                           new Uri("/word/document.xml", 
                           UriKind.Relative));
    
                    //Create the document part.
                    PackagePart pkgPart = 
    				pkg.CreatePart(docPartURI,docContentType);
    
                    //Add the data from XMLDocument to the document part.
                    Stream partStream = pkgPart.GetStream(
                        FileMode.Create, FileAccess.Write);
                       
                    xDoc.Save(partStream);
    
                    //Create a relationship between the document part
                    //and the package.
                    PackageRelationship pkgRelationship = 
                            pkg.CreateRelationship(docPartURI,
                            TargetMode.Internal,docRelationshipType, "rId1");
                    
                    
                    //Flush the changes, and then close the package.
                    pkg.Flush();
                    pkg.Close();
                    
                    return true;
    
                }
                catch (Exception ex)
                {
                    //Display a message to the user the indicates that an error
                    //occurred, and then return a result of false.
                    MessageBox.Show("An error occurred creating the document." +
                        " " + ex.Message,"Error Creating Document",
                        MessageBoxButtons.OK,MessageBoxIcon.Error);
                    return false;
                }
            }
    
  6. 在 Visual 有关 Studio 的 2005 年单击在 调试 菜单上的 启动调试
  7. 单击 创建 Excel 工作簿。此时将显示一个消息框,指示已成功创建工作簿的并在桌面上创建一个 HelloWorld.xlsx 文件。
  8. 在 Excel 2007 中打开该工作簿。请注意 Excel 2007 中打开的工作簿和 工作表 Sheet1 工作表包含文字"Hello World"。
  9. 单击 创建 Word 文档。此时将显示一个消息框,指示已成功创建文档时,并在桌面上创建一个 HelloWorld.docx 文件。
  10. 在 Word 2007 中打开文档。请注意在 Word 打开的文档和文档包含文字"Hello World"。

属性

文章编号: 931866 - 最后修改: 2007年2月27日 - 修订: 1.3
这篇文章中的信息适用于:
  • Microsoft Visual Studio 2005 Professional
  • Microsoft Visual Studio 2005 Standard Edition
  • Microsoft Visual Studio 2005 Express Edition
  • Microsoft Office Excel 2007
  • Microsoft Office Word 2007
  • Microsoft .NET Framework 3.0
  • Microsoft Visual C# 2005 Express Edition
关键字:?
kbmt kbexpertiseinter kbhowto KB931866 KbMtzh
机器翻译
注意:这篇文章是由无人工介入的微软自动的机器翻译软件翻译完成。微软很高兴能同时提供给您由人工翻译的和由机器翻译的文章, 以使您能使用您的语言访问所有的知识库文章。然而由机器翻译的文章并不总是完美的。它可能存在词汇,语法或文法的问题,就像是一个外国人在说中文时总是可能犯这样的错误。虽然我们经常升级机器翻译软件以提高翻译质量,但是我们不保证机器翻译的正确度,也不对由于内容的误译或者客户对它的错误使用所引起的任何直接的, 或间接的可能的问题负责。
点击这里察看该文章的英文版: 931866
Microsoft和/或其各供应商对于为任何目的而在本服务器上发布的文件及有关图形所含信息的适用性,不作任何声明。 所有该等文件及有关图形均"依样"提供,而不带任何性质的保证。Microsoft和/或其各供应商特此声明,对所有与该等信息有关的保证和条件不负任何责任,该等保证和条件包括关于适销性、符合特定用途、所有权和非侵权的所有默示保证和条件。在任何情况下,在由于使用或运行本服务器上的信息所引起的或与该等使用或运行有关的诉讼中,Microsoft和/或其各供应商就因丧失使用、数据或利润所导致的任何特别的、间接的、衍生性的损害或任何因使用而丧失所导致的之损害、数据或利润不负任何责任。

提供反馈

 

Contact us for more help

Contact us for more help
Connect with Answer Desk for expert help.
Get more support from smallbusiness.support.microsoft.com