12
2012
04

C# 打开Excel文件,并将标题加载到ComboBox中

private void btnOpenFile_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDailog1 = new OpenFileDialog();
openFileDailog1.Filter = "Excel 文件(*.xls)|*.xls|所有文件(*.*)|*.*";
if (openFileDailog1.ShowDialog() == DialogResult.OK)
{
btnSendMail.Enabled = true; //打开Excel文件时激活发送按钮

sFileName = openFileDailog1.FileName;
//MessageBox.Show(sFileName);

Excel = new Excel.Application(); //实例化Excel对象
xBook = Excel.Workbooks._Open(sFileName,
Missing.Value, Missing.Value, Missing.Value, Missing.Value
, Missing.Value, Missing.Value, Missing.Value, Missing.Value
, Missing.Value, Missing.Value, Missing.Value, Missing.Value);


xSheet = (Excel.Worksheet)xBook.Sheets[1]; //获取Sheets1表

string val;
int x;

cboCols.Items.Clear();
for (x = 1; x < 100; x++) //遍历标题
{
char ch = (char)(64 + x);
Excel.Range rng1 = xSheet.get_Range(ch + "1", Type.Missing);
if (rng1.Value2 == null)
{
break;
}
val = rng1.Value2.ToString();
if (val.Length == 0)
{
break;
}
//ComboBoxItem cbi1 = new ComboBoxItem();
cboCols.Items.Add(val);
}

maxCols = x - 1;
xBook.Close(Missing.Value, Missing.Value, Missing.Value); //关闭Excel里面的值
xBook = null; //
Excel.Quit();
Excel = null;
}
}
« 上一篇下一篇 »

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。