不清楚每个文件中是否只有一条记录。
假设您在单个文件中的数据是:
名称:N1 地址:A1 W. X, Y - Z 联系号码:C1 网卡号码:I1 名称:N2 地址:A2 W. X, Y - Z 联系号码:C2 网卡号码:I2
所以一行有 2 条记录(但可能更多)
姓名:N1 地址:A1 W. X, Y - Z 联系电话:C1 网卡编号:I1
姓名:N2 地址:A2 W. X, Y - Z 联系电话:C2 网卡编号:I2
我认为用空格分隔并不实用,因为名称和地址等字段可能包含空格。理想情况下,冒号 (:) 仅用作键和值之间的分隔符,不用于任何值。否则解决方案会变得更加复杂。
另外,我假设键的顺序保证如上例所示:
Name
Address
Contact No
NIC No
使用自定义对象列表或DataTable 来保存您的结构化数据。
在这个例子中,我将使用DataTable:
var separators = new char[] { ':' };
var data = new DataTable();
data.Columns.Add("Name", typeof(string));
data.Columns.Add("Address", typeof(string));
data.Columns.Add("ContractNo", typeof(string));
data.Columns.Add("NICNo", typeof(string));
对于每个有记录的文件,打开文件,读取文件内容并“处理”它:
foreach (string fileName in fileNames)
{
//read file content
string fileContent = ...;
string[] tokens = fileContent.Split(separators);
//we skip first token. It will always be 'Name'.
for(int i = 0; i < (tokens - 1) / 4; i++)
{
var record = data.NewRow();
string token = tokens[i * 4 + 1];
record["Name"] = token.Substring(0, token.Lenght - 7).Trim(); // Remove 'Address' from end and trim spaces
token = tokens[i * 4 + 2];
record["Address"] = token.Substring(0, token.Length - 10).Trim(); //Remove 'Contact No' from end and trim spaces
token = tokens[i * 4 + 3];
record["ContractNo"] = token.Substring(0, token.Length - 6).Trim(); //Remove 'NIC No' from end and trim spaces
token = tokens[i * 4 + 4];
if (token.EndsWith('Name')) //if there are multiple records
token = token.Substring(0, token.Length - 4);
record["NICNo"] = token.Trim();
data.Rows.Add(record);
}
}
如果每个文件仅包含一条记录,这也将起作用。
现在您已经在数据表中拥有了结构化数据,应该很容易将它们插入到 Excel 工作表中。