0

I have 3 sepereate datatables in C# I want to export to a single Excel Workbook, each on different sheets. Is there an easy way to do this? I thought about adding the tables to a single dataset, but that didn't seem possible. I wrote a method that can convert a single dataTable into a csv file, but that doesn't work for multiple tables. Thanks!

I used the first link and it's creating an Excel, but then it crashes for two reasons: The way it resized the columns didn't work:

// Resize the columns 
oRange = oSheet.get_Range(oSheet.Cells[1, 1],
    oSheet.Cells[rowCount, dt.Columns.Count]);

And I added this to make a second sheet and it didn't work:

Excel.Worksheet sheet2;
oWB.Sheets.Add(name[1], Type.Missing, Type.Missing, Type.Missing); 
sheet2 = (Excel.Worksheet)oWB.Sheets[1];

I can figure out how to fix my code and add another sheet, but does anyone know why the resize columns isn't working?

Raidri
  • 17,258
  • 9
  • 62
  • 65
Miriam
  • 59
  • 1
  • 3
  • "Didn't work" is pretty vague - what happened instead of it working? did you get an error message? If so, what was it? You have a typo here `Excel.Worksheet sheet 2` (extra space). `Sheets.Add()` returns the new sheet, so you can just use `sheet2 = oWB.Sheets.Add(...)` – Tim Williams Jul 27 '12 at 22:20

1 Answers1

0

http://msmvps.com/blogs/deborahk/archive/2009/07/23/writing-data-from-a-datatable-to-excel.aspx

Just add another sheet and export the second and third tables to the new sheets

Another link with details:

C# how to add Excel Worksheet programmatically Office XP / 2003

Make sure you catch the return.

xlNewSheet = (Worksheet)xlSheets.Add(xlSheets[1], Type.Missing, Type.Missing, Type.Missing);
Community
  • 1
  • 1
JeremyK
  • 1,075
  • 1
  • 22
  • 45
  • Thanks! I tried adding sheets but I caused a problem. Also, it's throwing an exception at the line: oRange = oSheet.get_Range(oSheet.Cells[1, 1], oSheet.Cells[rowCount, dt.Columns.Count]); saying there isn't a get_Range. It's a great start so thanks again! :) – Miriam Jul 27 '12 at 21:12
  • @Miriam - update your question with the problem code: very difficult to debug a single line! – Tim Williams Jul 27 '12 at 21:14