The filteredRange obtained after the execution of AutoFilter has two Areas, the first is the header row, and the second is the data rows.
If we get the value directly from the filteredRange without any operation, we will only get the first one, so no matter how much data is left after filtering, you will only get the header row.
Moreover, from the picture, you seem to be filtering the State column, that is, the 10th column, and the parameter passed in your code is 4.
ConvertRangeToDataTable does need some modification to resolve those two Areas.
My modified sample code is as follows:
private Range filteredRange = null;
private void button1_Click(object sender, EventArgs e)
{
Application xlApp = new Application();
Workbook xlWorkbook = xlApp.Workbooks.Open(@"D:\test\excel\1.xlsx");
Worksheet xlWorksheet = (Worksheet)xlWorkbook.Sheets[1];
try
{
Range xlRange = xlWorksheet.UsedRange;
//In the sample file I created, State is in the 4th column, you should use 10.
xlRange.AutoFilter(4, "Florida", XlAutoFilterOperator.xlFilterValues, Type.Missing, true);
filteredRange = xlRange.SpecialCells(XlCellType.xlCellTypeVisible, XlSpecialCellsValue.xlTextValues);
if (filteredRange != null)
{
System.Data.DataTable dt = ConvertRangeToDataTable();
if (dt != null) { dataGridView1.DataSource = dt; }
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
xlWorkbook.Save();
xlWorkbook.Close();
xlApp.Quit();
}
}
private System.Data.DataTable ConvertRangeToDataTable()
{
try
{
System.Data.DataTable dt = new System.Data.DataTable();
Range titleRange = filteredRange.Areas[1];
Range valueRange = filteredRange.Areas[2];
int ColCount = valueRange.Columns.Count;
int RowCount = valueRange.Rows.Count;
for (int i = 1; i <= ColCount; i++)
{
dt.Columns.Add(((Range)titleRange.Cells[1, i]).Value2.ToString());
}
var re = valueRange.Value2;
for (int i = 1; i <= RowCount; i++)
{
DataRow dr = dt.NewRow();
for (int j = 1; j <= ColCount; j++) { dr[j - 1] = ((Range)valueRange.Cells[i, j]).Value2; }
dt.Rows.Add(dr);
}
return dt;
}
catch
{
//do something here.
return null;
}
}
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.