我使用以下代码将剪贴板中的Excel数据读入C#数据表。从this answer到this question,代码相对没有变化。然后,我将数据表作为数据源添加到DataGridView控件进行操作。
但是,在我的Excel数据中,我需要保留空白/空单元格,此代码不会执行此操作(空白单元格被跳过,有效地压缩每一行,不会留空空间;空单元格从Excel XML)。如何在传输到数据表时保留空单元格?
方法:
private DataTable ParseClipboardData(bool blnFirstRowHasHeader)
{
var clipboard = Clipboard.GetDataObject();
if (!clipboard.GetDataPresent("XML Spreadsheet")) return null;
StreamReader streamReader = new StreamReader((MemoryStream)clipboard.GetData("XML Spreadsheet"));
streamReader.BaseStream.SetLength(streamReader.BaseStream.Length - 1);
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml(streamReader.ReadToEnd());
XNamespace ssNs = "urn:schemas-microsoft-com:office:spreadsheet";
DataTable dt = new DataTable();
var linqRows = xmlDocument.fwToXDocument().Descendants(ssNs + "Row").ToList<XElement>();
for (int x = 0; x < linqRows.Max(a => a.Descendants(ssNs + "Cell").Count()); x++)
dt.Columns.Add("Column " + x.ToString());
int intCol = 0;
DataRow currentRow;
linqRows.ForEach(rowElement =>
{
intCol = 0;
currentRow = dt.Rows.Add();
rowElement.Descendants(ssNs + "Cell")
.ToList<XElement>()
.ForEach(cell => currentRow[intCol++] = cell.Value);
});
if (blnFirstRowHasHeader)
{
int x = 0;
foreach (DataColumn dcCurrent in dt.Columns)
dcCurrent.ColumnName = dt.Rows[0][x++].ToString();
dt.Rows.RemoveAt(0);
}
return dt;
}
扩展方法:
public static XDocument fwToXDocument(this XmlDocument xmlDocument)
{
using (XmlNodeReader xmlNodeReader = new XmlNodeReader(xmlDocument))
{
xmlNodeReader.MoveToContent();
var doc = XDocument.Load(xmlNodeReader);
return doc;
}
}
举例说明:(Excel 2015)
Excel中的范围,复制到剪贴板
答案 0 :(得分:1)
如果前一个单元格缺失(具有空值),则单元格的xml将具有Index属性。您可以更新代码以检查列索引是否已更改,然后再将其复制到数据表行。
linqRows.ForEach(rowElement =>
{
intCol = 0;
currentRow = dt.Rows.Add();
rowElement.Descendants(ssNs + "Cell")
.ToList<XElement>()
.ForEach(cell =>
{
int cellIndex = 0;
XAttribute indexAttribute = cell.Attribute(ssNs + "Index");
if (indexAttribute != null)
{
Int32.TryParse(indexAttribute.Value, out cellIndex);
intCol = cellIndex - 1;
}
currentRow[intCol] = cell.Value;
intCol++;
});
});