最小的Excel文档

这是一个空白的Excel文档,只有一个WorkSheet。能省略的东西我都省略了。

实现环境:Visual Studio 2010, OpenXml SDK 2.0.50727

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml.Packaging;

namespace OpenXmlCreatExcelDocument
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            string strPath = null;
            SaveFileDialog objSaveFileDialog = new SaveFileDialog();
            objSaveFileDialog.Filter = "Excel Document (*.xlsx)|*.xlsx";
            objSaveFileDialog.ShowDialog();
            strPath = objSaveFileDialog.FileName;
            if (strPath.Length > 0)
            {
                using (SpreadsheetDocument objDocument = 
                    SpreadsheetDocument.Create(strPath, 
SpreadsheetDocumentType.Workbook))
                {
                    WorkbookPart objWorkbookPart = 
                        objDocument.AddWorkbookPart();
                    WorksheetPart objWorksheetPart =
                         objWorkbookPart.AddNewPart<WorksheetPart>();
                    string strWorkSheetPartrId =
                         objWorkbookPart.GetIdOfPart(objWorksheetPart);
                    objWorksheetPart.Worksheet = new Worksheet();
                    SheetData objSheetData = new SheetData();
                    objWorksheetPart.Worksheet.Append(objSheetData);
                    Sheets objSheets = new Sheets();
                    Sheet objSheet = new Sheet() 
                    { 
                        Name = "MySheet", 
                        SheetId = (UInt32Value)1U, 
                        Id = strWorkSheetPartrId 
                    };
                    objSheets.Append(objSheet);
                    objWorkbookPart.Workbook = new Workbook();
                    objWorkbookPart.Workbook.Append(objSheets);
                }
            }
        }
    }

相关资源: http://download.csdn.net/detail/tx_officedev/3926471

你可能感兴趣的:(Excel)