C#高效导出Excel(IList转DataTable,DataSet)

微软的Excel操作类导出Excel会很慢,此方法简单的把表中内容以字符串的形式写入到Excel中,用到的一个技巧就是"\t".

C#中的\t相当于Tab键,写入到Excel中时就是一列一列中写入。

#region 导出Excel
public void WriteExcel(DataTable ds, string path)
{
long totalCount = ds.Rows.Count;
Thread.Sleep(1000);
long rowRead = 0;
float percent = 0;

StreamWriter sw = new StreamWriter(path, false, Encoding.GetEncoding("gb2312"));
StringBuilder sb = new StringBuilder();
for (int k = 0; k < ds.Columns.Count; k++)
{
sb.Append(ds.Columns[k].ColumnName.ToString() + "\t");
}
sb.Append(Environment.NewLine);
for (int i = 0; i < ds.Rows.Count; i++)
{
for (int j = 0; j < ds.Columns.Count; j++)
{
sb.Append(ds.Rows[i][j].ToString() + "\t");
}
sb.Append(Environment.NewLine);
}
sw.Write(sb.ToString());
sw.Flush();
sw.Close();
}
public DataTable IListOut(IList<Users> list)
{
DataTable dt = new DataTable();

//此处遍历IList的结构并建立同样的DataTable
System.Reflection.PropertyInfo[] p = list[0].GetType().GetProperties();
foreach (System.Reflection.PropertyInfo pi in p)
{
dt.Columns.Add(pi.Name, System.Type.GetType(pi.PropertyType.ToString()));
}

for (int i = 0; i < list.Count; i++)
{
ArrayList TempList = new ArrayList();
//将IList中的一条记录写入ArrayList
foreach (System.Reflection.PropertyInfo pi in p)
{
object obj = pi.GetValue(list[i], null);
TempList.Add(obj);
}

object[] itm = new object[p.Length];
//遍历ArrayList向object[]里放数据
for (int j = 0; j < TempList.Count; j++)
{
itm.SetValue(TempList[j], j);
}
//将object[]的内容放入DataTable
dt.LoadDataRow(itm, true);
}
//返回DataTable
return dt;
}


#endregion

 

public ActionResult Index()
{
string connString = "Data Source=.;database=Test;uid=sa;pwd=123456";
SqlConnection con = new SqlConnection(connString);
con.Open();
string cmdText = "select * from User$";
SqlCommand cmd = new SqlCommand(cmdText,con);
SqlDataAdapter da = new SqlDataAdapter(cmdText,con);
DataSet ds=new DataSet ();
da.Fill(ds);

//正则表达式

string phone = @"^13[0-9]{9}|020[0-9]{8}|[0-9]{8}$";
//string mail=@"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
//string email = @"(\w*)@(\w*).com";
string mail = @"\s*([\w-]+(\.\w+)*@([\w-]+\.)+\w{2,3})\s*";

Regex rx = new Regex(phone);
Regex rx2 = new Regex(mail);

List<Users> user = new List<Users>();
List<Users> user2 = new List<Users>();
IList<Users> list=ds.ToList<Users>();

bool b=false;
bool b1 = false;
foreach (var item in list)
{
// if (!string.IsNullOrEmpty(item.CellPhone))
// {
// b = Regex.IsMatch(item.CellPhone, phone);
// }

////b1 = Regex.IsMatch(item.NickName,pattern);
// if (b == true)
// {
// user.Add(item);
// }

if (!string.IsNullOrEmpty(item.CellPhone))
{
if (rx2.IsMatch(item.Mail) && rx.IsMatch(item.CellPhone))
{
// 有电话号码的
user.Add(item);
}
else
{
//没有电话号码的
user2.Add(item);
}

}
else
{
user2.Add(item);
}

 


}
ViewBag.Users = user;

ViewBag.Users2 = user2;

DataTable dt = IListOut(user);
WriteExcel(dt, "d:\\a.xls");
DataTable dt1 = IListOut(user2);
WriteExcel(dt1, "d:\\b.xls");
con.Close();
return View();
}

你可能感兴趣的:(Datatable)