Datatable 到 string
public static string DataTableToString(DataTable dt)
{
//!@&,#$%,^&*為字段的拼接字符串
//為了防止連接字符串不在DataTable數據中存在,特意將拼接字符串寫成特殊的字符!
StringBuilder strData = new StringBuilder();
StringWriter sw = new StringWriter();
//DataTable 的當前數據結構以 XML 架構形式寫入指定的流
dt.WriteXmlSchema(sw);
strData.Append(sw.ToString());
sw.Close();
strData.Append("@&@");
for (int i = 0; i < dt.Rows.Count;i++) //遍歷dt的行
{
DataRow row = dt.Rows[i];
if (i > 0) //從第二行數據開始,加上行的連接字符串
{
strData.Append("#$%");
}
for (int j = 0; j < dt.Columns.Count; j++) //遍歷row的列
{
if (j > 0) //從第二個字段開始,加上字段的連接字符串
{
strData.Append("^&*");
}
strData.Append(Convert.ToString(row[j])); //取數據
}
}
return strData.ToString();
}
string 到Datatable
public static DataTable StringToDataTable(string strdata)
{
if (string.IsNullOrEmpty(strdata))
{
return null;
}
DataTable dt = new DataTable();
string[] strSplit = {"@&@"};
string[] strRow = {"#$%"}; //分解行的字符串
string[] strColumn = {"^&*"}; //分解字段的字符串
string[] strArr = strdata.Split(strSplit, StringSplitOptions.None);
StringReader sr = new StringReader(strArr[0]);
dt.ReadXmlSchema(sr);
sr.Close();
string strTable = strArr[1]; //取表的數據
if (!string.IsNullOrEmpty(strTable))
{
string[] strRows = strTable.Split(strRow, StringSplitOptions.None); //解析成行的字符串數組
for (int rowIndex = 0; rowIndex < strRows.Length; rowIndex++) //行的字符串數組遍歷
{
string vsRow = strRows[rowIndex]; //取行的字符串
string[] vsColumns = vsRow.Split(strColumn, StringSplitOptions.None); //解析成字段數組
dt.Rows.Add(vsColumns);
}
}
return dt;
}