日期:2014-05-19  浏览次数:21192 次

请问如何用C#连EXCEL做不规则表头的报表呢 谢谢!
EXCEL表头很不规则,而且是多级的,如:
    A          B        C
  A1|A2|A3    B1   |   B2|   B3     C1|C2

  10     20     30                 test1   test2   30                   40     50  

这时前面两行为表头行,第三行为数据行,这时我取得表头的字符串格式应该为:
A|A1,A|A2,A|A3,B|B1,B|B2,B|B3,C|C1,C|C2
取得数据对应的字符串应该为(数据中不存在,):
10,20,30,test1,test2,30,40,50
有可能更多级的,请问这样子我该怎么样取得表头跟EXCEL中的数据呢?有知道的吗?谢谢。

------解决方案--------------------
方案1:
可以先在Excel中把手工操作过程的宏录制下来
在把VB脚本翻译成C#、或者直接调用那段宏,参考如下代码:
Sub Macro1()
Range( "E2:E13 ").Select
With Selection.Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
xlBetween, Formula1:= "=$I$1:$I$5 "
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = " "
.ErrorTitle = " "
.InputMessage = " "
.ErrorMessage = " "
.IMEMode = xlIMEModeNoControl
.ShowInput = True
.ShowError = True
End With
End Sub

//项目-> 添加引用-> COM-> Microsoft Excel XX.X Object Library
using Excel = Microsoft.Office.Interop.Excel;
using Microsoft.Office.Interop.Excel;
using Microsoft.Office.Core;
using Microsoft.Vbe.Interop;

Excel.Application vExcel = new Excel.Application();
vExcel.Workbooks.Add(true);
vExcel.Visible = true;
Worksheet vWorksheet = (Worksheet)vExcel.Worksheets[1];
Range vRange = vWorksheet.get_Range( "E2 ", "E13 ");
vRange.Select();
vRange.Validation.Delete();
vRange.Validation.Add(XlDVType.xlValidateList,
XlDVAlertStyle.xlValidAlertStop,
XlFormatConditionOperator.xlBetween, "=$I$1:$I$5 ", null);

vRange.Validation.IgnoreBlank = true;
vRange.Validation.InCellDropdown = true;
vRange.Validation.InputTitle = " ";

vRange.Validation.ErrorTitle = " ";
vRange.Validation.InputMessage = " ";
vRange.Validation.ErrorMessage = " ";
vRange.Validation.IMEMode = (int)XlIMEMode.xlIMEModeNoControl;
vRange.Validation.ShowInput = true;
vRange.Validation.ShowError = true;

//-----------直接调用脚本-----------
//如果出现“不信任到Visual Basic Project 的程序连接”提示
//解决办法:开Excel-> 工具-> 宏-> 安全性-> 可靠发行商
//选中 "信任对于Visiual Basic 项目的访问 ",确定即可。
CodeModule vCodeModule = vExcel.ActiveWorkbook.VBProject.VBComponents.Add(
vbext_ComponentType.vbext_ct_StdModule).CodeModule;
vCodeModule.AddFromString(
@ "Sub MyMacro() " + "\r\n " +
@ " With Range( " "E2:E13 " ").Validation " + "\r\n " +
@ " .Delete " + "\r\n " +
@ " .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _ " + "\r\n " +
@ " xlBetween, Formula1:= " "=$I$1:$I$5 " " " + "\r\n " +
@ " .IgnoreBlank = True " + "\r\n " +
@ " .InCellDropdown = True " + "\r\n " +
@ " .InputTitle = " " " " " + "\r\n " +
@ " .ErrorTitle = " " " " " + "\r\n " +
@ " .InputMessage = " " " " " + "\r\n " +
@ " .ErrorMessage = " " " " " + "\r\n " +