如何使用c#从Excel文件绑定组合框
本文关键字:绑定 组合 文件 Excel 何使用 | 更新日期: 2023-09-27 18:03:30
我只想从myExcel.xls文件中的数据绑定一个组合框。我的代码是:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
string strWB = @"'myExcel.xls";
string strWBPath = @"C:'Users'Abid'Dropbox'Graphics'TEMP";
xlApp = new Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Open(strWBPath + strWB, 0, true, 5, "", "",
true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "'t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
Excel.Range xlRange = xlWorkSheet.get_Range("A1", "A4");
foreach (object item in xlRange)
{
comboBox1.Items.Add(item).ToString();
comboBox1.Text = comboBox1.Items.Count.ToString();
comboBox1.Text = comboBox1.Items.Add(item).ToString();
// listBox1.Items.Add(item).ToString();
}
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Unable to release the Object" + ex.ToString());
}
finally
{
GC.Collect();
}
}
}
}
这是不工作,你…当我按Ctrl+F5并单击Button1时,组合框与系统绑定。__ ComObject . .这个System._CommObject是什么?
这样做
var item = ((Range)worksheet.Cells[rowIndex, columnIndex]).Value2.ToString()
然后将项目绑定到组合框
int start = 1;
int end = 10;
for(start; start < end; start++)
{
var item = ((Range)xlWorkBook .Cells[rowIndex, columnIndex]).Value2.ToString();
comboBox1.Items.Add(item);
}