<?xml version="1.0"?> <ColumnsSeting xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <Columns> <Co ...
<?xml version="1.0"?> <ColumnsSeting xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <Columns> <Column> <ColumnName>custCode</ColumnName> <ColumnChinese>客戶編碼</ColumnChinese> <RegContent></RegContent> <DataType></DataType> </Column> <Column> <ColumnName>custName</ColumnName> <ColumnChinese>客戶名稱</ColumnChinese> <RegContent></RegContent> <DataType></DataType> </Column> <Column> <ColumnName>materialCode</ColumnName> <ColumnChinese>物料編碼</ColumnChinese> <RegContent></RegContent> <DataType></DataType> </Column> <Column> <ColumnName>materialName</ColumnName> <ColumnChinese>物料名稱</ColumnChinese> <RegContent></RegContent> <DataType></DataType> </Column> <Column> <ColumnName>num</ColumnName> <ColumnChinese>數量</ColumnChinese> <RegContent>^(-)?(([1-9]{1}\\d*)|([0]{1}))(\\.(\\d){0,})?$</RegContent> <DataType>數字</DataType> </Column> <Column> <ColumnName>unit</ColumnName> <ColumnChinese>單位</ColumnChinese> <RegContent></RegContent> <DataType></DataType> </Column> <Column> <ColumnName>money</ColumnName> <ColumnChinese>金額</ColumnChinese> <RegContent>^(-)?(([1-9]{1}\\d*)|([0]{1}))(\\.(\\d){0,})?$</RegContent> <DataType>數字</DataType> </Column> </Columns> </ColumnsSeting>用於匹配Excel格式的XML配置內容
/// <summary> /// 根據xml字典逐個單元格比較驗證DataTable數據格式 /// </summary> /// <param name="dt">Excel表格轉化為的DataTable</param> /// <param name="xmlpath">列名和列標題、格式化正則、格式類型xml配置文件路徑</param> public static void CompareColumnFormat(DataTable dt, string xmlpath) { if (dt == null) return; XmlDocument xmldoc = XmlUtility.GetXmlDocument(xmlpath); XmlNode root = xmldoc.SelectSingleNode("ColumnsSeting"); XmlNode subNode = root.SelectSingleNode("Columns"); XmlNodeList subNodeList = subNode.ChildNodes; for (int i = 0; i < subNodeList.Count; i++) { string colname = XmlUtility.GetElement(subNodeList[i], "ColumnName"); string colchinese = XmlUtility.GetElement(subNodeList[i], "ColumnChinese"); string regcontent = XmlUtility.GetElement(subNodeList[i], "RegContent"); string coldatatype = XmlUtility.GetElement(subNodeList[i], "DataType"); for (int j = 0; j < dt.Rows.Count; j++) { if (dt.Columns[i].ColumnName.Equals(colname)) { string curval = Convert.ToString(dt.Rows[j][i]); Regex reg = new Regex(regcontent); if (!reg.IsMatch(curval)) { throw new Exception(string.Format("當前表格中【{0}】的第【{1}】行數據【{2}】的格式不正確,應為【{3}】,\n請修正後繼續。", colchinese, j + 1, curval, coldatatype)); } } } } }