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
    {
    }
}
原文地址:https://www.cnblogs.com/SkySoot/p/2345322.html