大神们求教Winform Excel2007导出数据的连接代码 可以自定义标题的那种

解决方案 »

  1.   

    NPOI,可以设置字体、颜色、大小
      

  2.   

    用Microsoft.ACE.OLEDB.12.0 驱动
      

  3.   

    必须先要下载安装Microsoft.ACE.OLEDB.12.0 驱动
    /// <summary>///     ''' 读取 Excel 表格数据///     ''' </summary>///     ''' <param name="strExcelFilePath">Excel文件</param>///     ''' <param name="SheetName">工作区表名称</param>///     ''' <param name="SqlString">SQL查询语句</param>///     ''' <param name="lpDataTable">返回(DataTable)数据表</param>///     ''' <param name="bRowTitle">第一行是否为标题字段名</param>///     ''' <returns></returns>
    public bool GetExcelTable(string strExcelFilePath, string SheetName, string SqlString, ref DataTable lpDataTable, bool bRowTitle)
    {
        bool bFlag = true;
        try
        {
            // 注意:由于 Microsoft.ACE.OLEDB.12.0 驱动是32位,所以在编译选项必须勾选“首选32位”,否则会报错:未在本地计算机上注册“Microsoft.ACE.OLEDB.12.0”提供程序
            // String strConnString  = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strExcelFilePath & ";Extended Properties='Excel 8.0;HDR=YES'";
            string strConnString = "";
            if (bRowTitle)
                // 第一行为标题字段名
                strConnString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strExcelFilePath + ";Extended Properties='Excel 12.0;HDR=YES'";
            else
                // 字段名以:F1,F2,F3 ......
                strConnString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strExcelFilePath + ";Extended Properties='Excel 12.0;HDR=No'";
            using (OleDbConnection connection = new OleDbConnection(strConnString))
            {
                connection.Open();
                DataSet ds = null/* TODO Change to default(_) if this is not a reference type */;
                string mSQL = SqlString;
                OleDbDataAdapter odda = new OleDbDataAdapter(mSQL, connection);
                ds = new DataSet();
                odda.Fill(ds, SheetName);
                lpDataTable = ds.Tables(0);            connection.Close();
                odda.Dispose(); 
                odda = null;
                ds.Dispose();
                ds = null;
            }
        }
        catch (Exception ex)
        {
            bFlag = false;
            MessageBox.Show(ex.Message, "错误信息", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        return bFlag;
    }
            private void button1_Click(object sender, EventArgs e)
            {
                DataTable dt;
                string mSql = "select * from [工作表名$]";
                bool bVal = GetExcelTable("D:\Text.xsl", "工作表名", mSql, ref dt, true);
            }