我已经为此工作了 2 天,我有 excel 文件包含类型和数字,我需要获取特定类型的所有数字,
我尝试过这个,但对我不起作用:
public void ReadExcel(string SelectedType)
{
string excelName = "";
OpenFileDialog dialogRead = new OpenFileDialog();
dialogRead.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
dialogRead.ShowDialog();
excelName = dialogRead.FileName;
Application excelApp = new Application();
Workbook workbook = excelApp.Workbooks.Open(excelName);
Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook
.Sheets["INVENTORY "];
FilterByCellValue(worksheet, "V", SelectedType);
string newFilePath = "FilteredExcelFile.xlsx";
workbook.SaveAs(newFilePath);
excelApp.Quit();
}
static void FilterByCellValue(Microsoft.Office.Interop.Excel.Worksheet worksheet, string column, string cellValue)
{
Range dataRange = worksheet.UsedRange;
Range filterColumn = (Range)dataRange.Columns[column];
filterColumn.AutoFilter(1, cellValue, XlAutoFilterOperator.xlFilterValues, Type.Missing, true);
}
我期望获得选择类型的所有数字,但我得到这个异常_Range类的AutoFilter方法失败
正确过滤范围。这是我为您创建的一个示例。
using Excel = Microsoft.Office.Interop.Excel;
namespace WinFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
// Hardcoded Excel filename. Change as applicbale
string excelName = "C:\\Temp\\Book1.xlsx";
Excel.Application excelApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
excelApp = new Excel.Application{Visible = true};
xlWorkBook = excelApp.Workbooks.Open(excelName);
// Change the name of the sheet here
xlWorkSheet = xlWorkBook.Sheets["Sheet1"];
// I have hardcoded the filter value. change as applicable
string SelectedType = "4";
FilterByCellValue(xlWorkSheet, "V", SelectedType);
}
static void FilterByCellValue(Excel.Worksheet worksheet, string column, string cellValue)
{
object misValue = System.Reflection.Missing.Value;
Excel.Range dataRange = worksheet.UsedRange;
// Get the column number where you want to filter
int ColNumber = worksheet.Range[column + 1].Column;
// Filter the data range
dataRange.AutoFilter2(ColNumber, cellValue, Excel.XlAutoFilterOperator.xlFilterValues, misValue, true);
}
}
}
截图
之前
之后