Click here to Skip to main content
15,885,546 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want copy all the datas in my sql table to Excel file. How to do it using vb.net.

Please help me
Posted
Comments
Varun Sareen 5-Mar-12 8:01am    
http://www.codeproject.com/Answers/340490/hi-how-to-import-sql-table-data-to-excel-sheet-in#answer3

Already answered

1 solution

There are some articles on this site for exporting to Excel. There might be one that will do a datatable to spreadsheet conversion. I have done some work on exporting to Excel, and the framework makes it quite easy.
You will have to do some customization to make it work, but this should give you a start:

C#
private static void Excel(string fileName, List<IDirectoryInventoryDataCollector> list)
{
  try
  {
    var xlApp = new Excel.Application();
    var xlWorkBook = xlApp.Workbooks.Add();
    var xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
    ExcelTitleRow(list[0], 1, xlWorkSheet);

    int row = 2;
    foreach (var item in list)
    {
      ExcelFillRow(item, row++, xlWorkSheet);
    }

    for (int i = 1; i < list[0].MaxLevel - 1; i++)
    {
      ((Range)xlWorkSheet.Columns[i]).ColumnWidth = 2;
    }
    ((Range)xlWorkSheet.Columns[list[0].MaxLevel - 1]).ColumnWidth = 30;
    ((Range)xlWorkSheet.Rows[1]).WrapText = true;
    ((Range)xlWorkSheet.Rows[1]).HorizontalAlignment = HorizontalAlignment.Center;
    ((Range)xlWorkSheet.Cells[1, 1]).WrapText = false;

    xlWorkBook.SaveAs(fileName);
    xlWorkBook.Close();
    xlApp.Quit();
  }
  catch (AccessViolationException)
  {
    System.Windows.Forms.MessageBox.Show(
       "Have encountered access violation. This could be issue with Excel 2000 if that is only version installed on computer",
       "Access Violation");
  }
  catch (Exception)
  {
    System.Windows.Forms.MessageBox.Show("Unknown error",
       "Unknown error");
  }
}

private static void ExcelFillRow(IDirectoryInventoryDataCollector item, int row, Excel.Worksheet sheet)
{
  sheet.Cells[row, item.Level] = item.Name;
  int column = item.MaxLevel;
  foreach (var property in item.GetProperties())
  {
    sheet.Cells[row, column++] = property;
  }
}

private static void ExcelTitleRow(IDirectoryInventoryDataCollector item, int row, Excel.Worksheet sheet)
{
  sheet.Cells[row, 1] = "Name";
  int column = item.MaxLevel;
  foreach (var property in item.GetPropertyNames())
  {
    sheet.Cells[row, column++] = property;
  }
}


You will need to add a reference to Microsoft.Office.Interop.Excel
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900