C# datatable 读取数据库

C# datatable 读取数据库,第1张

public SqlConnection getcon()

{

//连接本地数据库 server=localhost

string M_str_sqlcon = @"server=localhostdatabase=表名Integrated Security=SSPI"

SqlConnection myCon = new SqlConnection(M_str_sqlcon)

return myCon

}

/// <summary>

/// 创建一个DataTable对象

/// </summary>

/// <param name="M_str_sqlstr">SQL语句</param>

/// <param name="M_str_table">表名</param>

/// <returns>返回DataTable对象</returns>

DataTable mytable = new DataTable()

public DataTable gettable(string M_str_sqlstr)

{

SqlConnection sqlcon = this.getcon()

SqlDataAdapter sqlda = new SqlDataAdapter(M_str_sqlstr, sqlcon)

sqlda.Fill(mytable)

sqlcon.Close()

sqlcon.Dispose()

return mytable

}

调用该方法:

DataTable mytable = gettable("select * from 表名")

/// <summary>

        /// 读取Excel文件为DataTable,使用Aspose.Cells.dll

        /// </summary>

        /// <param name="filepath"> Excel文件的全路径 </param>

        /// <returns> DataTable</returns>

        public static DataTable ExcelToDataTable(string filepath)

        {

            DataTable dt = new DataTable()

            try

            {

                if (!File .Exists(filepath))

                {

                    MessageBox.Show(@"文件不存在!" ,@"提示")

                    return null 

                }

                Aspose.Cells. Workbook workbook = new Aspose.Cells.Workbook()

                workbook.Open(filepath)

                Aspose.Cells. Worksheet worksheet = workbook.Worksheets[0]

                dt = worksheet.Cells.ExportDataTable(0, 0, worksheet.Cells.MaxDataRow + 1, worksheet.Cells.MaxColumn + 1, true )//showTitle  

                return dt

            }

            catch (System.Exception e)

            {

                return null 

            }

        }

存数据库就自己写吧,数据都有了


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/sjk/9886850.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-03
下一篇 2023-05-03

发表评论

登录后才能评论

评论列表(0条)

保存