C# WPF 讀寫Excel文件


下載NPOI開源庫 http://npoi.codeplex.com/releases

引用“dotnet4”文件夾內DLL

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;  
    }  
    /// 將excel中的數據導入到DataTable中  
    /// <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);  
            workbook = WorkbookFactory.Create(fs);  
            if (sheetName != null)  
            {  
                sheet = workbook.GetSheet(sheetName);  
                //如果沒有找到指定的sheetName對應的sheet,則嘗試獲取第一個sheet  
                if (sheet == null)   
                {  
                    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)//打印錯誤信息  
        {  
            MessageBox.Show("Exception: " + ex.Message);  
            return null;  
        }  
    }  
  
    //將DataTable數據導入到excel中  
    //<param name="data">要導入的數據</param>  
    //<param name="sheetName">要導入的excel的sheet的名稱</param>  
    //<param name="isColumnWritten">DataTable的列名是否要導入</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;  
        }  
    }  
  
    public void Dispose()//IDisposable為垃圾回收相關的東西,用來顯式釋放非托管資源,這部分目前還不是非常了解  
    {  
        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 (ExcelHelper excelHelper = new ExcelHelper(@"I:\人員信息表.xlsx"))  
{  
    dt = excelHelper.ExcelToDataTable("MySheet", true);//讀取數據  
    foreach (DataRow dr in dt.Rows)//DataTable轉ObservableCollection  
    {  
        personalInfoList.Add(new personalInfo(dr[0].ToString(), Int32.Parse(dr[1].ToString()), dr[2].ToString(), dr[3].ToString()));  
    }  
}  
using (ExcelHelper excelHelper = new ExcelHelper(@"I:\寫入人員信息表.xlsx"))//定義一個范圍,在范圍結束時處理對象  
{  
    excelHelper.DataTableToExcel(dt, "MySheet", true);  
}  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM