简体   繁体   中英

How to Read an Excel file to DataGridView in C#

I'm having an issue reading an excel file onto a datagridview. After running the application, it keeps telling me

"The process cannot access the file 'C:\\Users\\emmanuel.adefuye\\Documents\\ExcelTestFile.xlsx' because it is being used by another process"

private void OpenExcelFile_Click(object sender, EventArgs e)
        {

             Excel.Application xlApp = new Excel.Application();
             Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(@"C:\\Users\\emmanuel.adefuye\\Documents\\ExcelTestFile.xlsx");
             Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
             Excel.Range xlRange = xlWorksheet.UsedRange;

             {
                 //String name = "First Name";
                 OpenFileDialog selectedFile = new OpenFileDialog();
                 selectedFile.ShowDialog();

                 selectedFile.OpenFile();

                 String constr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
                                 "C:\\Users\\emmanuel.adefuye\\Documents\\ExcelTestFile.xlsx" +
                                 ";Extended Properties='Excel 8.0;HDR=YES;';";

                 OleDbConnection con = new OleDbConnection(constr);
                 OleDbCommand oconn = new OleDbCommand("Select * From [" + selectedFile.SafeFileName + "$]", con);
                 con.Open();

                 OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
                 DataTable data = new DataTable();


                 sda.Fill(data);
                 dataGridView1.DataSource = data;
             }

             int rowCount = xlRange.Rows.Count;
             int colCount = xlRange.Columns.Count;

             //iterate over the rows and columns and print to the console as it appears in the file
             //excel is not zero based!!
             for (int i = 1; i <= rowCount; i++)
             {
                 for (int j = 1; j <= colCount; j++)
                 {
                     //new line
                     if (j == 1)
                         Console.Write("\r\n");

                     //write the value to the console
                     if (xlRange.Cells[i, j] != null && xlRange.Cells[i, j].Value2 != null)
                         Console.Write(xlRange.Cells[i, j].Value2.ToString() + "\t");
                 }
             }

             //cleanup
             GC.Collect();
             GC.WaitForPendingFinalizers();

             Marshal.ReleaseComObject(xlRange);
             Marshal.ReleaseComObject(xlWorksheet);

             //close and release
             xlWorkbook.Close();
             Marshal.ReleaseComObject(xlWorkbook);

             //quit and release
             xlApp.Quit();
             Marshal.ReleaseComObject(xlApp);


        }`

You could just use this great nuget package:

https://www.nuget.org/packages/NPOI/

and read excel like that:

    public static XSSFWorkbook ReadExcelFile(string strFilePath)
    {
        XSSFWorkbook hssfwb;
        using (FileStream file = new FileStream(strFilePath, FileMode.Open, FileAccess.Read))
        {
            hssfwb = new XSSFWorkbook(file);
        }
        return hssfwb;
    }
    private void OpenExcelFile_Click(object sender, EventArgs e)
    {
        var dt = ReadExcelFile(@"C:\\Users\\emmanuel.adefuye\\Documents\\ExcelTestFile.xlsx");
    }

There are a few different ways to read the data and manipulate it, but for your core issue of

"The process cannot access the file 'C:\\Users\\emmanuel.adefuye\\Documents\\ExcelTestFile.xlsx' because it is being used by another process"

Your issue is that you're opening the file here

Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(@"C:\\Users\\emmanuel.adefuye\\Documents\\ExcelTestFile.xlsx");

And then again attempting to access it here

OpenFileDialog selectedFile = new OpenFileDialog();
                 selectedFile.ShowDialog();

                 selectedFile.OpenFile();

                 String constr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
                                 "C:\\Users\\emmanuel.adefuye\\Documents\\ExcelTestFile.xlsx" +
                                 ";Extended Properties='Excel 8.0;HDR=YES;';";

                 OleDbConnection con = new OleDbConnection(constr);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM