且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在excel文件中选择指定列的值?

更新时间:2022-12-12 10:58:43

Hi,

请参阅下面的演示,检查它是否适合您的文件。

Please see the demo below to check if it suitable for your files.

这是一个winform应用程序。

This is a winform application.

请先在winform上添加一个文本框和一个列表框。

Please add a textbox and a listbox firstly on the winform.

添加引用:Microsoft.Office.Interop.Excel

Add reference: Microsoft.Office.Interop.Excel

添加行:使用Excel = Microsoft.Office.Interop.Excel;在命名空间之前。

Add line: using Excel = Microsoft.Office.Interop.Excel; before the namespace.

 

OpenFileDialog openFileDialog1 = new OpenFileDialog(); openFileDialog1.Filter = "Excel files|*.xlsx|All files|*.*"; if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) { string fileName = openFileDialog1.FileName; Excel.Application xlApp = new Excel.Application(); xlApp.Visible = false; Excel.Workbook xlWorkBook = xlApp.Workbooks.Open(fileName); Excel.Worksheet xlWorksheet = xlWorkBook.ActiveSheet; Excel.Range currentFind = null; Excel.Range oRng = xlWorksheet.UsedRange; currentFind = oRng.Find(textBox1.Text, Type.Missing, Excel.XlFindLookIn.xlValues, Excel.XlLookAt.xlPart, Excel.XlSearchOrder.xlByRows, Excel.XlSearchDirection.xlNext, false, Type.Missing, Type.Missing); if (currentFind != null) { Excel.Range sRng = xlWorksheet.UsedRange.Columns[currentFind.Column]; listBox1.Items.Clear(); foreach (Excel.Range cell in sRng.Cells) { listBox1.Items.Add(cell.Value); } } else { MessageBox.Show("Not Found"); } xlWorkBook.Close(false); xlApp.Quit(); }