如何使用 Office XML 檔案格式和封裝元件從.NET Framework 3.0 建立簡單的 Excel 2007 活頁簿或簡單的 Word 2007 文件

文章翻譯 文章翻譯
文章編號: 931866 - 檢視此文章適用的產品。
全部展開 | 全部摺疊

在此頁中

簡介

本文將告訴您,如何使用 Microsoft Office XML 檔案格式和封裝元件從 Microsoft.NET Framework 3.0 建立簡單的 Microsoft Office Excel 2007 活頁簿或簡單的 Microsoft Office Word 2007 文件。

其他相關資訊

本文中的程式碼範例建立新的 Excel 活頁簿或新的 Word 文件,包含文字"Hello World"不含自動化 Excel 2007 或 Word 2007。

用戶端需求

  • Microsoft Visual Studio 2005 或 Microsoft Visual C# 2005
  • .NET Framework 3.0
  • .NET Framework 的 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] 索引標籤上,請按一下 [瀏覽] 索引標籤、 找出 C:\Program Files\Reference assemblies\Microsoft\Framework\v3.0 資料夾,然後按一下 [WindowsBase.dll
  4. Visual Studio 中按一下 [切換至程式碼檢視的 [檢視] 功能表上的 [程式碼]。
  5. Form1 類別中加入下列指示詞。
    	
    	using System.Xml;
    	using System.IO;
    	using System.IO.Packaging;
    
    

加入程式碼來建立 Excel 活頁簿

  1. Visual Studio 中按一下 [切換至表單的設計檢視的 [檢視] 功能表上的 [設計工具]。
  2. Windows 表單上新增 按鈕 控制項。設定 文字建立 Excel 活頁簿 按鈕的屬性。
  3. 按兩下 [按鈕] 控制項來產生 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. Visual Studio 中按一下 [切換至表單的設計檢視的 [檢視] 功能表上的 [設計工具]。
  2. Windows 表單上新增另一個 按鈕 控制項。將按鈕的 Text 屬性設定來 建立 Word 文件
  3. 按兩下 [按鈕] 控制項來產生 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 Edition
  • 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
機器翻譯
重要:本文是以 Microsoft 機器翻譯軟體翻譯而成,而非使用人工翻譯而成。Microsoft 同時提供使用者人工翻譯及機器翻譯兩個版本的文章,讓使用者可以依其使用語言使用知識庫中的所有文章。但是,機器翻譯的文章可能不盡完美。這些文章中也可能出現拼字、語意或文法上的錯誤,就像外國人在使用本國語言時可能發生的錯誤。Microsoft 不為內容的翻譯錯誤或客戶對該內容的使用所產生的任何錯誤或損害負責。Microsoft也同時將不斷地就機器翻譯軟體進行更新。
按一下這裡查看此文章的英文版本: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