Microsoft SDK for Open XML Formats Technology Preview 发布

下载地址:
http://go.microsoft.com/?linkid=6899996

帮助文档里有一个创建docx的例子,下面提供一个创建xlsx的例子

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Office.DocumentFormat.OpenXml.Packaging;
using System.IO;
using System.Xml;


namespace ConsoleApplication1
{
    
class Program
    
{
        
static void Main(string[] args)
        
{           
            CreateNewXlsDocument(
"c:\\temp.xlsx");
        }

        

        
public static void CreateNewXlsDocument(string document)
        
{         
            
using (SpreadsheetDocument doc = SpreadsheetDocument.Create(document, SpreadsheetDocumentType.Workbook))
            
{              

                WorkbookPart mainPart 
= doc.AddWorkbookPart();
                WorksheetPart part 
= mainPart.AddNewPart<WorksheetPart>();

                
string rid = mainPart.GetIdOfPart(part);

                SetWorkBookContect(mainPart,rid);
                SetWorkSheetContect(part);
            }

        }


        
public static void SetWorkBookContect(WorkbookPart part,string rid)
        
{
            
const string xlsXml = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?><workbook xmlns=""http://schemas.openxmlformats.org/spreadsheetml/2006/main"" xmlns:r=""http://schemas.openxmlformats.org/officeDocument/2006/relationships""><sheets><sheet name=""Sheet1"" sheetId=""1"" r:id=""{0}""/></sheets></workbook>";
            
using (Stream stream = part.GetStream())
            
{
                
byte[] buf = (new UTF8Encoding()).GetBytes(string.Format(xlsXml,rid));
                stream.Write(buf, 
0, buf.Length);
            }

        }



        
public static void SetWorkSheetContect(WorksheetPart part)
        
{
            
const string xlsXml =
         
@"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?>
<worksheet xmlns=""http://schemas.openxmlformats.org/spreadsheetml/2006/main"" xmlns:r=""http://schemas.openxmlformats.org/officeDocument/2006/relationships"">
  <sheetData>
    <row>
      <c t=""inlineStr"">
        <is>
          <t>测试</t>
        </is>
      </c>      
    </row>    
  </sheetData>
</worksheet>
";
                       
            
using (Stream stream = part.GetStream())
            
{
                
byte[] buf = (new UTF8Encoding()).GetBytes(xlsXml);
                stream.Write(buf, 
0, buf.Length);
            }

        }


    }

}

原文地址:https://www.cnblogs.com/derek/p/773932.html