Advertisement
Guest User

Untitled

a guest
Feb 17th, 2020
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.63 KB | None | 0 0
  1. private void button1_Click(object sender, EventArgs e)
  2. {
  3. string excelFinalPath = @"C:\Users\pulsani\Desktop\MS_Excel\data.xlsx";
  4. Microsoft.Office.Interop.Excel.Application application = new Microsoft.Office.Interop.Excel.Application();
  5. Workbook workBook = application.Workbooks.Open(excelFinalPath);
  6. /////////////////////////////////////////////////////////////////
  7. DataSet dataSet = new DataSet();
  8.  
  9. for (int i = 1; i <= workBook.Sheets.Count; i++)
  10. {
  11. Worksheet worksheet = workBook.Worksheets[i];
  12.  
  13. Range excelCell = worksheet.UsedRange;
  14. Object[,] sheetValues = (Object[,])excelCell.Value;
  15. int noOfRows = sheetValues.GetLength(0); // first dimention size
  16. int noOfColumns = sheetValues.GetLength(1);//second dimention size
  17.  
  18. //add column names to datatable
  19. System.Data.DataTable dataTable = new System.Data.DataTable();
  20. for (int j = 1; j <= noOfColumns; j++)
  21. {
  22. dataTable.Columns.Add(new DataColumn(((Range)worksheet.Cells[1, j]).Value));
  23. }
  24.  
  25. //as first column has header, start at second row
  26. for (int k = 2; k <= noOfRows; k++)
  27. {
  28. DataRow dataRow = dataTable.NewRow();
  29. for (int l = 1; l <= noOfColumns; l++)
  30. {
  31. dataRow[l - 1] = ((Range)worksheet.Cells[k, l]).Value;
  32. }
  33. dataTable.Rows.Add(dataRow);
  34. }
  35. dataSet.Tables.Add(dataTable);
  36. }
  37. /////////////////////////////////////////////////////////////////
  38. workBook.Close(false, excelFinalPath, null);
  39. Marshal.ReleaseComObject(workBook);
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement