C#讀取Excel文件(通過OleDb連接,把excel文件作為數據源來讀取)


首先看下本示例的操作界面:

image

 

代碼如下:

/// <summary>
/// 導入文件
/// </summary>
private void btnImport_Click(object sender, EventArgs e)
{
    if (dlgFileOpen.ShowDialog() == DialogResult.OK)
    {
        filename = dlgFileOpen.FileName;
        DataSet ds = LoadDataFromExcel(filename);
        if (ds != null && ds.Tables.Count != 0)
        {
            SaveDate(ds);
        }
    }
}

/// <summary>
/// 將選定的 Excel 數據轉換成 DatatSet 數據集
/// </summary>
/// <param name="filename">文件名</param>
private DataSet LoadDataFromExcel(string filename)
{
    try
    {
        string strConn;
        // IMEX=1 可把混合型作為文本型讀取,避免null值
         strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filename 
                + ";Extended Properties='Excel 8.0;HDR=False;IMEX=1'";
        OleDbConnection OleConn = new OleDbConnection(strConn);
        OleConn.Open();
        String sql = "SELECT * FROM  [Sheet1$]"; // 可更改 Sheet 名稱    
         OleDbDataAdapter OleDaExcel = new OleDbDataAdapter(sql, OleConn); DataSet ds = new DataSet();
        OleDaExcel.Fill(ds, "Sheet1");
        OleConn.Close();
        return ds;
    }
    catch (Exception ex)
    {
        MessageBox.Show("數據綁定Excel失敗!失敗原因:" + ex.Message, "提示信息", MessageBoxButtons.OK, 
            MessageBoxIcon.Information);
        return null;
    }
}
/// <summary>
/// 保存到 Excel 文件
/// </summary>
/// <param name="excelTable">要保存到文件的 table</param>
/// <param name="filePath">物理路徑</param>
/// <returns>成功或失敗</returns>
public static bool SaveDataTableToExcel(System.Data.DataTable excelTable, string filePath)
{
    Microsoft.Office.Interop.Excel.Application app = 
        new Microsoft.Office.Interop.Excel.ApplicationClass();
    try
    {
        app.Visible = false;
        Workbook wBook = app.Workbooks.Add(true);
        Worksheet wSheet = wBook.Worksheets[1] as Worksheet;
        if (excelTable.Rows.Count > 0)
        {
            int row = 0;
            row = excelTable.Rows.Count;
            int col = excelTable.Columns.Count;
            for (int i = 0; i < row; i++)
            {
                for (int j = 0; j < col; j++)
                {
                    string str = excelTable.Rows[i][j].ToString();
                    wSheet.Cells[i + 2, j + 1] = str;
                }
            }
        }
 
        int size = excelTable.Columns.Count;
        for (int i = 0; i < size; i++)
        {
            wSheet.Cells[1, 1 + i] = excelTable.Columns[i].ColumnName;
        }
 
        //設置禁止彈出保存和覆蓋的詢問提示框    
        app.DisplayAlerts = false;
        app.AlertBeforeOverwriting = false;
 
        //保存工作簿    
        wBook.Save();
 
        //保存excel文件    
        app.Save(filePath);
        app.SaveWorkspace(filePath);
        app.Quit();
        app = null;
        return true;
    }
    catch (Exception err)
    {
        MessageBox.Show("導出Excel出錯!錯誤原因:" + err.Message, "提示信息",
            MessageBoxButtons.OK, MessageBoxIcon.Information);
        return false;
    }
    finally
    {
    }
}


免責聲明!

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



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