日期:2014-05-18  浏览次数:20990 次

dataGridView加载二维表头的Excel
dataGridView加载一个excel表,excel表里面有二维表头,怎样在加载完后,dataGridView列头显示的也是二维的样子。
  看了些资料,理出的思路是:1.判断是不是二维表头。2.如果是重绘列头(但是不知道代码怎么写, Orz..)。 不知道对不对,有代码的请教教我吧。

------解决方案--------------------
读取excel代码,生成xml
public XmlDocument ReadExcelConfig(string excelFileName)
{

Excel.Application xlApp = new Excel.ApplicationClass();

if (xlApp == null)
{
System.Windows.Forms.MessageBox.Show("EXCEL could not be started. Check that your office installation and project references are correct.");
return null;
}


Excel.Workbook xlWorkBook = xlApp.Workbooks.Open(excelFileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing);

Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

Excel.Range excelRange = xlWorkSheet.UsedRange;

int RowCount = excelRange.Rows.Count;

int ColCount = excelRange.Columns.Count;

ReportDataGridConfig config = new ReportDataGridConfig(RowCount, ColCount);

/*--------------------------------------读取数据-----------------------------------------------*/
for (Int32 i = 1; i <= RowCount; i++)
{
for (Int32 j = 1; j <= ColCount; j++)
{
Excel.Range cellRange = (Excel.Range)excelRange.Cells[i, j];

XmlElement XmlCellElement = config.GetCellConfig(i - 1, j - 1); // 单元格

if ((bool)cellRange.MergeCells) // 合并单元格
{
Int32 RowSpan = cellRange.MergeArea.Rows.Count;
Int32 ColSpan = cellRange.MergeArea.Columns.Count;
Int32 RowOffset = i - cellRange.MergeArea.Row;
Int32 ColOffset = j - cellRange.MergeArea.Column;

Int32 MergeMode = 0x0001;

if (RowOffset == 0 && ColOffset == 0)
MergeMode = MergeMode | 0x1000;

if (ColOffset == ColSpan - 1)
MergeMode = MergeMode | 0x0100;

if (RowOffset == RowSpan - 1)
MergeMode = MergeMode | 0x0010;

XmlCellElement.SetAttribute("MergeMode", MergeMode.ToString());

XmlCellElement.SetAttribute("RowSpan", Convert.ToString(RowSpan));
XmlCellElement.SetAttribute("ColSpan", Convert.ToString(ColSpan));

XmlCellElement.SetAttribute("RowOffset", Convert.ToString(RowOffset));
XmlCellElement.SetAttribute("ColOffset", Convert.ToString(ColOffset));

Excel.Range cellStartRange = (Excel.Range)excelRange.Cells[cellRange.MergeArea.Row, cellRange.MergeArea.Column];

if (cellStartRange.Value2 == null)
XmlCellElement.InnerText = "";
else
XmlCellElement.InnerText = cellStartRange.Value2.ToString();
}