相信大家程序中,一有和excel交互的地方的时候,就会去用微软的excel的那些操作类,呵呵,本人以前也是这样,但是非常的烦躁那些类,并且,有的时候,调用以后,释放不掉,呵呵。
同时,看见别人网上说不用这些dll都可以导出,我就实在是没弄明白,最近,做一系统的时候,正好碰到别人机器上没装excel,但是,偏偏要导出这个东西,因此,非常的头疼。
后来想了个折中的办法,呵呵,既然excel是微软开发的,并且excel里面的格子也算是table吧,呵呵,那 可不可以直接把一个table存如一个文件,然后保存为xls就行了撒。
代码非常的简单
public void ExportSelectData(string fileName)
{
StringBuilder strBuilder=new StringBuilder();
strBuilder.Append(@"<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN'>");
strBuilder.Append(@"<html>");
strBuilder.Append(@"<head>");
strBuilder.Append(@"<title>Document</title>");
strBuilder.Append(@"<meta HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=utf-8'>");
strBuilder.Append(@"</head>");
strBuilder.Append(@"<body>");
strBuilder.Append(@"<table style='border-right: black thin solid; border-top: black thin solid; border-left: black thin solid; border-bottom: black thin solid'>");
strBuilder.Append("<tr>");
foreach (PropertyStyle style in mPropertyStyles)
{
string str = string.Format(@"<td style='border-right: black thin solid; border-top: black thin solid; border-left: black thin solid; border-bottom: black thin solid;background-color: lightgrey'>{0}</td>", Convert.ToString(style.DisplayName));
strBuilder.Append(str);
}
strBuilder.Append("</tr>");
foreach (AlarmView alarmView in SelectedAlarmViews)
{
if (alarmView != null && alarmView.Wrapper != null && mPropertyStyles != null)
{
strBuilder.Append("<tr>");
AlarmWrapperPropertyHelper propertyHelper = new AlarmWrapperPropertyHelper(alarmView.Wrapper);
propertyHelper.NullValue = null;
foreach (PropertyStyle style in mPropertyStyles)
{
object value = propertyHelper.GetValue(style);
strBuilder.Append(HtmlTextSerialize.Draw(value));
}
strBuilder.Append("</tr>");
}
}
strBuilder.Append("</table>");
strBuilder.Append("</body>");
strBuilder.Append("</html>");
using (StreamWriter write = new StreamWriter(fileName))
{
write.Write(strBuilder.ToString());
write.Close();
}
}
主要是拼写一个tabel,同时,该方法能够满足excel的导出,和导出到html,实际上,我们可以把文件保存到html,然后改变后缀名就可以的,当然,本程序,只要传入一个文件路径就可以了,不用管是xls,还是html。
这样的excel导出,没有测试加图片什么的,但是,我相信,图片也是可以的