比較簡單的將資料資訊匯入wrod文檔方案(C# for word)

來源:互聯網
上載者:User

複製代碼 代碼如下:/// <summary>
/// 設定Word模板,word表格樣式在此設定
/// </summary>
/// <param name="dsTr"></param>
/// <returns></returns>
protected string SetWordTemplate(string dsTr)
{
StringBuilder html = new StringBuilder();
html.Append("<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>");
html.Append("<html xmlns='http://www.w3.org/1999/xhtml'>");
html.Append("<html><head><title>測試word</title></head>");
html.Append("<body>");
//html.Append("<table cellpadding='0' cellspacing='0' border='1'>");
html.Append(dsTr);
//html.Append("</table>");
html.Append("</body>");
html.Append("</html>");
return html.ToString();
}
/// <summary>
/// 儲存Word
/// </summary>
/// <param name="savePath"></param>
/// <param name="data"></param>
/// <returns></returns>
protected bool SaveWord(string savePath,string data)
{
try
{
using (StreamWriter sw = new StreamWriter(savePath,true, Encoding.Default))
{
sw.WriteLine(data);
sw.Close();
sw.Dispose();
}
return true;
}
catch
{
return false;
}
return false;
}
/// <summary>
/// 匯入
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
//儲存路徑
string path = string.Format("{0}{1}", Application.StartupPath, "儲存實體路徑");
//多個表 這裡的dataset需要換成從資料庫查詢出來的dataset
foreach(DataTable dt in new DataSet().Tables)
{
StringBuilder _tables = new StringBuilder();
for (int i = 0; i < dt.Rows.Count; i++ )
{
if (i == 0)
{
_tables.Append("<table cellpadding='0' cellspacing='0' border='1'>");
_tables.Append("<tr><td>表名字</td></tr>");
}
_tables.Append("<tr><td>" + i + "</td><td>" + i + "</td><td>" + i + "</td></tr>");
if (i == (dt.Rows.Count - 1))
_tables.Append("</table>");
}
SaveWord(path, this.SetWordTemplate(_tables.ToString()));
}
MessageBox.Show("產生成功!");
}

   嘿嘿!大功告成啦!這種方法快捷,但是不能設定word其他的分頁功能等等,不過應對於從資料庫中把所有表匯入到wrod是綽綽有餘啦!~
   俺乃小小小小鳥兒,如過哪位大大大大鳥有更好的方案好的Code請多多指教哦!~Thanks

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.