为什么每次我通过键入XML或通过C#插入超过21个用户时,我的Excel被损坏?

我写了一个程序,可以提取用户名,并通过XML将它们添加到一个Excel工作表; 然而,每当有超过21个用户,Excel的损坏。 如果我通过记事本编辑.xls文件,我可以通过删除或添加超过22个用户来修复或破坏它。

如果我通过xml插入超过21个用户,Excel文件总是被损坏。

这是添加用户的代码,但这并不重要,因为即使手动执行也可以复制损坏问题。

public static void XlFormat(string[] nameSplit, DataTable dt, string[] lines, String path) { lines = new string[dt.Rows.Count]; for (int i = 0; i < dt.Rows.Count; i++) //When I change the condition to i < 22 or lower, it will create a perfect file. More than 22 and it gets corrupted { lines[i] = "<Row><Cell ss:StyleID=\"s59\"><Data ss:Type=\"String\">" + dt.Rows[i][1] + "</Data></Cell>" + "<Cell ss:StyleID=\"s59\"><Data ss:Type=\"String\">" + dt.Rows[i][2] + "</Data></Cell>" + "<Cell ss:StyleID=\"s59\"><Data ss:Type=\"String\">" + dt.Rows[i][3] + "</Data></Cell>" + "<Cell ss:StyleID=\"s59\"><Data ss:Type=\"String\">" + dt.Rows[i][4] + "</Data></Cell>" + "<Cell ss:StyleID=\"s64\"/><Cell ss:StyleID=\"s65\"/></Row>"; } /* Insert the data into designated points in excel_format.txt using regular */ /* expressions, including the cells for each user. It should be all in one */ /* final string. */ string linesCombined = ""; for (int i = 0; i < lines.Count(); i++) { linesCombined += lines[i]; } string xmlLines = Regex.Replace(excelFormat, "--- INSERT USERS HERE ---", linesCombined); xmlLines = Regex.Replace(xmlLines, "--- INSERT LEADER HERE ---", nameSplit[2]); xmlLines = Regex.Replace(xmlLines, "--- INSERT DATE HERE ---", DateTime.Now.Date.ToString()); xmlLines = Regex.Replace(xmlLines, "--- INSERT EMAIL HERE ---", nameSplit[1]); xmlLines = Regex.Replace(xmlLines, "--- INSERT GROUP HERE ---", nameSplit[0]); /* Write the final string to an XLS file. This file type will open in Excel as a */ /* spreadsheet even though it was written as an XML file. */ System.IO.File.Delete(@"" + path + nameSplit[0] + ".xls"); System.IO.File.WriteAllText(@"" + path + nameSplit[0] + ".xls", xmlLines); } 

我什么时候把我的XLS限制在22个用户?

看看你给的excelFormat项目的文件,我猜这是由于下面的行:

 <Table ss:ExpandedColumnCount="7" ss:ExpandedRowCount="68" x:FullColumns="1" x:FullRows="1" ss:DefaultRowHeight="15"> 

你可以看到它提到了一个设置为68的ExpandedRowCount 。在同一个文件中快速search<Row得到44个结果。 如果你添加你的22行,这会使你达到66,这只有2短。 我不太清楚哪里出了问题,因为仍然有2的差异,但我猜这是你的问题。 尝试将ExpandedRowCount属性更改为更高的值并再次testing(less于22个项目,正好22个项目,超过22个项目)。