C#Excel的匯入與匯出

來源:互聯網
上載者:User

標籤:

1、整個Excel表格叫做工作表:WorkBook(工作薄),包含的叫頁(工作表):Sheet;行:Row;儲存格Cell。

2、NPOI是POI的C#版本,NPOI的行和列的index都是從0開始

3、POI讀取Excel有兩種格式一個是HSSF,另一個是XSSF。 HSSF和XSSF的區別如下: 
HSSF is the POI Project‘s pure Java implementation of the Excel ‘97(-2007) file format. 
XSSF is the POI Project‘s pure Java implementation of the Excel 2007 OOXML (.xlsx) file format. 
即:HSSF適用2007以前的版本,XSSF適用2007版本及其以上的。

下面是用NPOI讀寫Excel的例子:ExcelHelper封裝的功能主要是把DataTable中資料寫入到Excel中,或者是從Excel讀取資料到一個DataTable中。

 ExcelHelper類:

using System;using System.Collections.Generic;using System.Linq;using System.Text;using NPOI.SS.UserModel;using NPOI.XSSF.UserModel;using NPOI.HSSF.UserModel;using System.IO;using System.Data;namespace NetUtilityLib{    public class ExcelHelper : IDisposable    {        private string fileName = null; //檔案名稱        private IWorkbook workbook = null;        private FileStream fs = null;        private bool disposed;        public ExcelHelper(string fileName)        {            this.fileName = fileName;            disposed = false;        }        /// <summary>        /// 將DataTable資料匯入到excel中        /// </summary>        /// <param name="data">要匯入的資料</param>        /// <param name="isColumnWritten">DataTable的列名是否要匯入</param>        /// <param name="sheetName">要匯入的excel的sheet的名稱</param>        /// <returns>匯入資料行數(包含列名那一行)</returns>        public int DataTableToExcel(DataTable data, string sheetName, bool isColumnWritten)        {            int i = 0;            int j = 0;            int count = 0;            ISheet sheet = null;            fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);            if (fileName.IndexOf(".xlsx") > 0) // 2007版本                workbook = new XSSFWorkbook();            else if (fileName.IndexOf(".xls") > 0) // 2003版本                workbook = new HSSFWorkbook();            try            {                if (workbook != null)                {                    sheet = workbook.CreateSheet(sheetName);                }                else                {                    return -1;                }                if (isColumnWritten == true) //寫入DataTable的列名                {                    IRow row = sheet.CreateRow(0);                    for (j = 0; j < data.Columns.Count; ++j)                    {                        row.CreateCell(j).SetCellValue(data.Columns[j].ColumnName);                    }                    count = 1;                }                else                {                    count = 0;                }                for (i = 0; i < data.Rows.Count; ++i)                {                    IRow row = sheet.CreateRow(count);                    for (j = 0; j < data.Columns.Count; ++j)                    {                        row.CreateCell(j).SetCellValue(data.Rows[i][j].ToString());                    }                    ++count;                }                workbook.Write(fs); //寫入到excel                return count;            }            catch (Exception ex)            {                Console.WriteLine("Exception: " + ex.Message);                return -1;            }        }        /// <summary>        /// 將excel中的資料匯入到DataTable中        /// </summary>        /// <param name="sheetName">excel工作薄sheet的名稱</param>        /// <param name="isFirstRowColumn">第一行是否是DataTable的列名</param>        /// <returns>返回的DataTable</returns>        public DataTable ExcelToDataTable(string sheetName, bool isFirstRowColumn)        {            ISheet sheet = null;            DataTable data = new DataTable();            int startRow = 0;            try            {                fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);                if (fileName.IndexOf(".xlsx") > 0) // 2007版本                    workbook = new XSSFWorkbook(fs);                else if (fileName.IndexOf(".xls") > 0) // 2003版本                    workbook = new HSSFWorkbook(fs);                if (sheetName != null)                {                    sheet = workbook.GetSheet(sheetName);                    if (sheet == null) //如果沒有找到指定的sheetName對應的sheet,則嘗試擷取第一個sheet                    {                        sheet = workbook.GetSheetAt(0);                    }                }                else                {                    sheet = workbook.GetSheetAt(0);                }                if (sheet != null)                {                    IRow firstRow = sheet.GetRow(0);                    int cellCount = firstRow.LastCellNum; //一行最後一個cell的編號 即總的列數                    if (isFirstRowColumn)                    {                        for (int i = firstRow.FirstCellNum; i < cellCount; ++i)                        {                            ICell cell = firstRow.GetCell(i);                            if (cell != null)                            {                                string cellValue = cell.StringCellValue;                                if (cellValue != null)                                {                                    DataColumn column = new DataColumn(cellValue);                                    data.Columns.Add(column);                                }                            }                        }                        startRow = sheet.FirstRowNum + 1;                    }                    else                    {                        startRow = sheet.FirstRowNum;                    }                    //最後一列的標號                    int rowCount = sheet.LastRowNum;                    for (int i = startRow; i <= rowCount; ++i)                    {                        IRow row = sheet.GetRow(i);                        if (row == null) continue; //沒有資料的行預設是null                                                       DataRow dataRow = data.NewRow();                        for (int j = row.FirstCellNum; j < cellCount; ++j)                        {                            if (row.GetCell(j) != null) //同理,沒有資料的儲存格都預設是null                                dataRow[j] = row.GetCell(j).ToString();                        }                        data.Rows.Add(dataRow);                    }                }                return data;            }            catch (Exception ex)            {                Console.WriteLine("Exception: " + ex.Message);                return null;            }        }        public void Dispose()        {            Dispose(true);            GC.SuppressFinalize(this);        }        protected virtual void Dispose(bool disposing)        {            if (!this.disposed)            {                if (disposing)                {                    if (fs != null)                        fs.Close();                }                fs = null;                disposed = true;            }        }    }}

測試代碼:

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Data;namespace NPOIExcelExample{    class Program    {        static DataTable GenerateData()        {            DataTable data = new DataTable();            for (int i = 0; i < 5; ++i)            {                data.Columns.Add("Columns_" + i.ToString(), typeof(string));            }            for (int i = 0; i < 10; ++i)            {                DataRow row = data.NewRow();                row["Columns_0"] = "item0_" + i.ToString();                row["Columns_1"] = "item1_" + i.ToString();                row["Columns_2"] = "item2_" + i.ToString();                row["Columns_3"] = "item3_" + i.ToString();                row["Columns_4"] = "item4_" + i.ToString();                data.Rows.Add(row);            }            return data;        }        static void PrintData(DataTable data)        {            if (data == null) return;            for (int i = 0; i < data.Rows.Count; ++i)            {                for (int j = 0; j < data.Columns.Count; ++j)                    Console.Write("{0} ", data.Rows[i][j]);                Console.Write("\n");            }        }        static void TestExcelWrite(string file)        {            try            {                using (ExcelHelper excelHelper = new ExcelHelper(file))                {                    DataTable data = GenerateData();                    int count = excelHelper.DataTableToExcel(data, "MySheet", true);                    if (count > 0)                        Console.WriteLine("Number of imported data is {0} ", count);                }            }            catch (Exception ex)            {                Console.WriteLine("Exception: " + ex.Message);            }        }        static void TestExcelRead(string file)        {            try            {                using (ExcelHelper excelHelper = new ExcelHelper(file))                {                    DataTable dt = excelHelper.ExcelToDataTable("MySheet", true);                    PrintData(dt);                }            }            catch (Exception ex)            {                Console.WriteLine("Exception: " + ex.Message);            }        }        static void Main(string[] args)        {            string file = "..\\..\\myTest.xlsx";            TestExcelWrite(file);            TestExcelRead(file);        }    }}

簽於這篇文章閱讀量較高,更新一下我使用Aspose.Cells的另一個版本:

PS:Aspose是要收費的

using System;using System.Collections.Generic;using System.Data;using System.IO;using System.Linq;using System.Text;using Aspose.Cells;namespace NetUtilityLib{    public static class ExcelHelper    {        public static int DataTableToExcel(DataTable data, string fileName, string sheetName, bool isColumnNameWritten)        {            int num = -1;            try            {                Workbook workBook;                Worksheet worksheet = null;                if (File.Exists(fileName))                    workBook = new Workbook(fileName);                else                    workBook = new Workbook();                if (sheetName == null)                {                    if (workBook.Worksheets.Count > 0)                    {                        worksheet = workBook.Worksheets[0];                    }                    else                    {                        sheetName = "Sheet1";                        workBook.Worksheets.RemoveAt(sheetName);                        worksheet = workBook.Worksheets.Add(sheetName);                    }                }                if (worksheet != null)                {                    worksheet.Cells.Clear();                    num = worksheet.Cells.ImportDataTable(data, isColumnNameWritten, 0, 0, false);                    workBook.Save(fileName);                }            }            catch (Exception ex)            {                Console.WriteLine(ex.Message);            }            return num;        }        public static void AddOneRowToExcel(DataRow dataRow, string fileName, string sheetName)        {            try            {                Workbook workBook;                if (File.Exists(fileName))                    workBook = new Workbook(fileName);                else                    workBook = new Workbook();                Worksheet worksheet=null;                if (sheetName == null)                {                    worksheet = workBook.Worksheets[0];                }                else                {                    worksheet = workBook.Worksheets[sheetName];                }                if (worksheet != null)                {                    worksheet.Cells.ImportDataRow(dataRow, worksheet.Cells.MaxDataRow + 1,0);                    //worksheet.Cells.ImportArray(dataArray, worksheet.Cells.MaxDataRow+1, 0, false);                    workBook.Save(fileName);                }            }            catch (Exception ex)            {                Console.WriteLine(ex.Message);            }        }        public static DataTable ExcelToDataTable(string fileName, string sheetName, bool isFirstRowColumnName)        {            DataTable data = new DataTable();            try            {                Workbook workbook = null;                FileInfo fileInfo = new FileInfo(fileName);                if (fileInfo.Extension.ToLower().Equals(".xlsx"))                    workbook = new Workbook(fileName, new LoadOptions(LoadFormat.Xlsx));                else if (fileInfo.Extension.ToLower().Equals(".xls"))                    workbook = new Workbook(fileName, new LoadOptions(LoadFormat.Excel97To2003));                if (workbook != null)                {                    Worksheet worksheet = null;                    if (sheetName != null)                    {                        worksheet = workbook.Worksheets[sheetName];                    }                    else                    {                        worksheet = workbook.Worksheets[0];                    }                    if (worksheet != null)                    {                        data = worksheet.Cells.ExportDataTable(0, 0, worksheet.Cells.MaxRow+1, worksheet.Cells.MaxColumn+1,                            isFirstRowColumnName);                        return data;                    }                }                else                {                    return data;                }            }            catch (Exception ex)            {                Console.WriteLine(ex.Message);            }            return data;        }    }}
Excel相關DLL下載:NPOI-Lib.rar

1.NPOI:http://npoi.codeplex.com/releases/view/38113

2.NPOI學習系列教程推薦:http://www.cnblogs.com/tonyqus/archive/2009/04/12/1434209.html

C#Excel的匯入與匯出

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.