標籤:style blog color os io 檔案 資料 ar
1.現將資料庫中的資訊讀到DataTable中
2.用函數將DataTable轉為string
private string ConvertDataTableToXML(DataTable dt) { if (dt != null) { MemoryStream ms = null; XmlTextWriter XmlWt = null; try { ms = new MemoryStream(); XmlWt = new XmlTextWriter(ms, Encoding.Unicode); dt.TableName = "Table"; /*給DataTable一個名字,隨便起一個就行,沒實際意義,但不寫會報錯*/
dt.WriteXml(XmlWt, XmlWriteMode.WriteSchema); /*WriteXml方法為.Net自己封裝的方法,不支援overwrite,但.Net提供了多種WriteXml方法,可根據自己的需求選擇,WriteXml(XmlWt, XmlWriteMode.WriteSchema)會匯出一個表頭,方便之後將xml檔案重新匯入資料庫;WriteXml(XmlWt)匯出的xml檔案不包括表頭,會出現缺列問題,如果某一列資料為null,那麼那一列會不寫*/
int count = (int)ms.Length; byte[] temp = new byte[count]; ms.Seek(0, SeekOrigin.Begin); ms.Read(temp, 0, count); UnicodeEncoding ucode = new UnicodeEncoding(); string returnValue = ucode.GetString(temp).Trim(); return returnValue; } catch (System.Exception ex) { throw ex; } finally { if (XmlWt != null) { XmlWt.Close(); ms.Close(); ms.Dispose(); } } } else { return ""; } }
3.寫檔案
public void WriteStream(string sFileName, string sContent) { Response.ClearContent(); Response.AddHeader("content-disposition", "attachment; filename=" + sFileName); Response.ContentType = "text/xml"; Response.Write(sContent); Response.End(); }