Click here to Skip to main content
12,511,882 members (42,875 online)
Click here to Skip to main content

Stats

271.7K views
11.4K downloads
289 bookmarked
Posted

Read and write Open XML files (MS Office 2007)

, 31 Jul 2011 CPOL
Learn how to read and write Open XML files (MS Office 2007).
Excel2007ReadWrite
bin
Debug
Release
Excel2007ReadWrite.exe
ICSharpCode.SharpZipLib.dll
DLLs
ICSharpCode.SharpZipLib.dll
Input
In.xlsx
obj
Output
Properties
TEMP
Template.xlsx
XlsxReadWrite
XlsxReadWrite
bin
Release
ICSharpCode.SharpZipLib.dll
XlsxReadWrite.exe
Input
In.xlsx
Output
Properties
References
ICSharpCode.SharpZipLib.dll
TEMP
Template.xlsx
// Excel2007ReadWrite created by Zeljko Svedic. This source code is free to use, modify and 
// incorporate in your software products. This code is not owned by GemBoxSoftware.com or is
// related in any way to GemBox.Spreadsheet Free/Professional .NET component.

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace Excel2007ReadWrite
{
    public partial class ExcelRWForm : Form
    {
        private const string tempDir = @"..\..\TEMP";
        private const string templateFile = @"..\..\Template.xlsx";

        private DataTable data = new DataTable();

        public ExcelRWForm()
        {
            InitializeComponent();

            this.textBoxInput.Text = @"..\..\Input\In.xlsx";
            this.textBoxOutput.Text = @"..\..\Output\Out.xlsx";

            this.data.Columns.Add("ID", Type.GetType("System.Int32"));
            this.data.Columns.Add("FirstName", Type.GetType("System.String"));
            this.data.Columns.Add("LastName", Type.GetType("System.String"));

            this.dataGridView1.DataSource = data;
        }

        private void buttonSelectInput_Click(object sender, EventArgs e)
        {
            this.openFileDialog1.FileName = this.textBoxInput.Text;

            if (this.openFileDialog1.ShowDialog(this) == DialogResult.OK)
                this.textBoxInput.Text = this.openFileDialog1.FileName;
        }

        private void buttonSelectOutput_Click(object sender, EventArgs e)
        {
            this.saveFileDialog1.FileName = this.textBoxOutput.Text;

            if (this.saveFileDialog1.ShowDialog(this) == DialogResult.OK)
                this.textBoxOutput.Text = this.saveFileDialog1.FileName;
        }

        private void buttonReadInput_Click(object sender, EventArgs e)
        {
            // Get the input file name from the text box.
            string fileName = this.textBoxInput.Text;

            // Delete contents of the temporary directory.
            ExcelRW.DeleteDirectoryContents(ExcelRWForm.tempDir);

            // Unzip input XLSX file to the temporary directory.
            ExcelRW.UnzipFile(fileName, ExcelRWForm.tempDir);

            // Open XML file with table of all unique strings used in the workbook..
            FileStream fs = new FileStream(ExcelRWForm.tempDir + @"\xl\sharedStrings.xml",
                FileMode.Open, FileAccess.Read);
            // ..and call helper method that parses that XML and returns an array of strings.
            ArrayList stringTable = ExcelRW.ReadStringTable(fs);

            // Open XML file with worksheet data..
            fs = new FileStream(ExcelRWForm.tempDir + @"\xl\worksheets\sheet1.xml",
                FileMode.Open, FileAccess.Read);
            // ..and call helper method that parses that XML and fills DataTable with values.
            ExcelRW.ReadWorksheet(fs, stringTable, this.data);
        }

        private void buttonWriteOutput_Click(object sender, EventArgs e)
        {
            // Get the output file name from the text box.
            string fileName = this.textBoxOutput.Text;

            // Delete contents of the temporary directory.
            ExcelRW.DeleteDirectoryContents(ExcelRWForm.tempDir);

            // Unzip template XLSX file to the temporary directory.
            ExcelRW.UnzipFile(ExcelRWForm.templateFile, ExcelRWForm.tempDir);

            // We will need two string tables; a lookup Hashtable for fast searching and 
            // an ordinary ArrayList where items are sorted by their index.
            Hashtable lookupTable;

            // Call helper methods which creates both tables from input data.
            ArrayList stringTable = ExcelRW.CreateStringTables(this.data, out lookupTable);

            // Create XML file..
            FileStream fs = new FileStream(ExcelRWForm.tempDir + @"\xl\sharedStrings.xml",
                FileMode.Create);
            // ..and fill it with unique strings used in the workbook
            ExcelRW.WriteStringTable(fs, stringTable);

            // Create XML file..
            fs = new FileStream(ExcelRWForm.tempDir + @"\xl\worksheets\sheet1.xml",
                FileMode.Create);
            // ..and fill it with rows and columns of the DataTable.
            ExcelRW.WriteWorksheet(fs, this.data, lookupTable);

            // ZIP temporary directory to the XLSX file.
            ExcelRW.ZipDirectory(ExcelRWForm.tempDir, fileName);

            // If checkbox is checked, show XLSX file in Excel 2007.
            if (this.checkBoxOpenFile.Checked)
                System.Diagnostics.Process.Start(fileName);
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

ZeljkoS
President Gemmeus Ltd
United Kingdom United Kingdom
Zeljko Svedic, the owner of a component vendor company called GemBox Software.
GemBox Software provides .NET developers a GemBox components that enable easy and efficient processing of office files:
  • GemBox.Spreadsheet, a .NET component for reading, writing, converting and printing spreadsheet files (XLSX, XLS, ODS, CSV, HTML, PDF and XPS).
  • GemBox.Document, a .NET component for reading, writing, converting and printing document files (DOCX, DOC, PDF, HTML, XPS, RTF and TXT).
  • GemBox.Email, a .NET component for composing, receiving and sending email messages using IMAP, POP and SMTP.

You may also be interested in...

Pro
Pro
| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.160929.1 | Last Updated 31 Jul 2011
Article Copyright 2006 by ZeljkoS
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid