标签归档:c#

c#将DataTable中指定列转换成数组或List的方法分享


摘要:
日常c#开发中,我们常常需要将datatable中指定列转换为数组或list,下文将举例分享具体的实现方法,如下所示:

   --例:将DataTable dtTest中的info列转换为数组和List的方法
  
   string[]       arrInfo =  dtTest.AsEnumerable().Select(d => d.Field("info")).ToArray();
 
   List listInfo =  dtTest.AsEnumerable().Select(d => d.Field("info")).ToList();

c# asp.net 下载excel到本地的方法分享


摘要:
下面的代码可实现下载excel文件至客户端任意位置,如下:
实验环境:iis

例:
下载服务器端tmp目录下的指定excel文件至客户端

   try
{
    string strServerPath  = Server.MapPath("~") + "/tmp/20190823001.xlsx";//待下载服务器文件路径
    FileInfo  f= new FileInfo(strServerPath);
    Response.Clear();
    Response.Charset = "GB2312";
    Response.ContentEncoding = System.Text.Encoding.UTF8;
    Response.AddHeader("Content-Disposition", "attachment;filename=" + Server.UrlEncode(f.Name));
    Response.AddHeader("Content-Length", f.Length.ToString());
    Response.ContentType = "application/x-bittorrent";
    Response.WriteFile(f.FullName);
    Response.End();
}
catch (Exception ex)
{
    //异常处理
}

c# 虚拟一个DataTable 并添加数据的方法分享


摘要:
下文分享c#生成一个DataTable方法,如下所示:

---定义DataTable
    DataTable  tbMaoMao = new DataTable("maomao");
---定义一个数据列,并设置为自增长列

DataColumn tbColumn = null;
tbColumn = tbMaoMao.Columns.Add("keyId", Type.GetType("System.Int32"));
tbColumn.AutoIncrement = true;   //自增加列
tbColumn.AutoIncrementSeed = 1;//起始为1
tbColumn.AutoIncrementStep = 1;//步长为1
tbColumn.AllowDBNull = false; //禁止列值为null



dc = tbMaoMao.Columns.Add("info", Type.GetType("System.String"));     

DataRow tbRow; //定义一行
tbRow = tbMaoMao.NewRow();
tbRow["info"] = "sql爱好者"; 
tbMaoMao.Rows.Add(tbRow);

tbRow = tbMaoMao.NewRow();
tbRow["info"] = "猫猫小屋"; 
tbMaoMao.Rows.Add(tbRow);
----给dataTable添加数据行方法2 

tbMaoMao.Rows.Add(new object[]{null,"sqlserver"});
tbMaoMao.Rows.Add(new object[] { null, "sqlblogs"});