相信大家程式中,一有和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工作薄,如果表格行數超過了 65535以上,後面的資料,我想,應該是不能夠顯示的......
這樣的excel匯出,沒有測試加圖片什麼的,但是,我相信,圖片也是可以的(有測試,本機能夠顯示圖片,如果是把檔案下載到了別的機器上,應該是不能夠顯示圖片的,因為 如果按照程式的思路,應該是這樣的<td><img src="檔案路徑"></img></td>,這樣的方式,只是儲存著檔案的串連,如果真要在別的機器上都顯示圖片,也就只有按照這個'檔案路徑',在別的機器上組織出這個路徑出來,並把圖片儲存到該地方....excel中圖片的插入方式,應該是有兩中,一種是儲存圖片的串連,一種是把圖片包含到excel檔案中......)