Posts Tagged Interop

Write DataTable to an MS Word Table Efficiently with C# using a Dynamic Type

This is a C# adaptation of the code I wrote to write a datatable to a Microsoft Word document table for vb.net . But that doesn’t really begin to tell the story here. In vb.net we have been accustomed to being allowed to leave parameters empty when automating the creation of a table in Microsoft Word. C# has not permitted me that luxury which to be honest is probably a better code practice. So prepare to meet the Type.Missing object! In addition the default item that we learned to love/hate in Visual Basic for Applications (VBA) code years ago also is not used in C#. Finally in declaring the range object for the table it became an opportunity to use the new dynamic reference type keyword, which was designed for such situations. Check out this video on the subject which is quite excellent.

http://channel9.msdn.com/Shows/Going+Deep/Inside-C-40-dynamic-type-optional-parameters-more-COM-friendly/player?w=512&h=288

For these reasons you will see key differences between the two sets of code. Don’t forget to import Microsoft Word as a COM reference and do your import statements. As always feel free to comment or email. Have a great day!

using Office = Microsoft.Office.Core;
using Word = Microsoft.Office.Interop.Word;

public void CreateWordTableWithDataTable(DataTable dt)
        {
            int RowCount = dt.Rows.Count; int ColumnCount = dt.Columns.Count;
            Object[,] DataArray = new object[RowCount + 1, ColumnCount + 1];
            //int RowCount = 0; int ColumnCount = 0;
            int r = 0;
            for (int c = 0; c <= ColumnCount – 1; c++)
            {
                DataArray[r, c] = dt.Columns[c].ColumnName;
                for (r = 0; r <= RowCount – 1; r++)
                {
                    DataArray[r, c] = dt.Rows[r][c];
                } //end row loop
            } //end column loop

            Word.Document oDoc = new Word.Document();
            oDoc.Application.Visible = true;
            oDoc.PageSetup.Orientation = Word.WdOrientation.wdOrientLandscape;
           
            dynamic oRange = oDoc.Content.Application.Selection.Range;
            String oTemp = “”;
            for (r = 0; r <= RowCount – 1; r++)
            {
                for (int c = 0; c <= ColumnCount – 1; c++)
                {
                    oTemp = oTemp + DataArray[r, c] + “\t”;
                  
                }
            }

oRange.Text = oTemp;
           
object Separator = Word.WdTableFieldSeparator.wdSeparateByTabs;
object Format = Word.WdTableFormat.wdTableFormatWeb1;
object ApplyBorders = true;
object AutoFit = true;

object AutoFitBehavior = Word.WdAutoFitBehavior.wdAutoFitContent;
            oRange.ConvertToTable(ref Separator,
        ref RowCount, ref ColumnCount, Type.Missing, ref Format,
        ref ApplyBorders, Type.Missing, Type.Missing, Type.Missing,
         Type.Missing, Type.Missing, Type.Missing,
         Type.Missing, ref AutoFit, ref AutoFitBehavior,
         Type.Missing);
           
            oRange.Select();
            oDoc.Application.Selection.Tables[1].Select();
            oDoc.Application.Selection.Tables[1].Rows.AllowBreakAcrossPages = 0;
            oDoc.Application.Selection.Tables[1].Rows.Alignment = 0;
            oDoc.Application.Selection.Tables[1].Rows[1].Select();
            oDoc.Application.Selection.InsertRowsAbove(1);
            oDoc.Application.Selection.Tables[1].Rows[1].Select();

            //gotta do the header row manually
            for (int c = 0; c <= ColumnCount – 1; c++)
            {
               oDoc.Application.Selection.Tables[1].Cell(1, c + 1).Range.Text = dt.Columns[c].ColumnName;
            }

            oDoc.Application.Selection.Tables[1].Rows[1].Select();
            oDoc.Application.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                      
                    }

Facebook

, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,

Leave a comment

Write Data From DataTable To Excel With an Array Using C#

This is actually a redo of code written in vb.net a while back that dumps data from a datatable in a dataset into an excel spreadsheet in an effective and fast manner. I am always getting asked how to do this in C# so I decided to put that up today. Yes, I do C# too! Just didn’t want to admit it….

It’s pretty self explanatory. Don’t forget to clean up your excel instance when done. If you have any questions please feel free to send me an email.

Import an excel reference and at the top of your code you need your import statements. Then simply pass your dataset and datatable (granted you could just pass the datatable – I had my reasons for passing the dataset too at the time) to the method. The array is declared as an object because sometimes the compiler has to deal with unforeseen data issues that might arise and it has been effective for me to do let it handle those situations as they arise. I hope you find this useful.

using Excel = Microsoft.Office.Interop.Excel;
using Office = Microsoft.Office.Core;

public void CreateSpreadSheetFromDataSet(DataSet ds, DataTable dt)
        {

            Excel.Application Excel = new Excel.Application();
            Excel.Visible = true;
            Excel.Worksheet WSheet = new Excel.Worksheet();
            Excel.Workbooks.Add();
            WSheet = Excel.ActiveWorkbook.ActiveSheet;
            int rows = ds.Tables[dt.TableName].Rows.Count;
            int columns = ds.Tables[dt.TableName].Columns.Count;
            int r = 0; int c = 0;
            object[,] DataArray = new object[rows + 1, columns + 1];
            for (c = 0; c <= columns – 1; c++)
            {
                DataArray[r, c] = ds.Tables[dt.TableName].Columns[c].ColumnName;
                for (r = 0; r <= rows – 1; r++)
                {
                    DataArray[r, c] = ds.Tables[dt.TableName].Rows[r][c];
                } //end row loop
            } //end column loop

//actually write array to Excel Spreadsheet
            WSheet.Range["A2"].Resize[rows, columns].Value = DataArray;

            //write header row to spreadsheet
            int DataTableColumnCounter;
            int ExcelColumnCounter = 1; //excel spreadsheets start at 1 when counting columns not zero!
            for (DataTableColumnCounter = 0; DataTableColumnCounter <= ds.Tables[dt.TableName].Columns.Count – 1; DataTableColumnCounter++)
            {
                WSheet.Cells[1, ExcelColumnCounter].Value = ds.Tables[dt.TableName].Columns[DataTableColumnCounter].ColumnName;
                ExcelColumnCounter = ExcelColumnCounter + 1; //moving to next column
            }
        }

My Facebook Link

, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,

Leave a comment

Follow

Get every new post delivered to your Inbox.