Click here to Skip to main content
15,880,796 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am struggling last few days to print data table value in particular excel column.

I have the master table with data.

When i print master table data to excel, there is a condition to swap the column based on the reference table data
and print.

step1
-----
Read the master table. screen shot below

Master Table


step2
-----
While printing the data into excel, first refer the column as mentioned below and swap the column and then print

Reference Column


step3
-----
Final Output in the excel after swaping the columns.

Note : pls. note down the master table and output in excel, there will be swaping the columns.
since the column has been refrenced.

Output Template

My Source Code :

pls. have a look inside the code, and let me know where we have to change the code to print appropriate columns in excel...

Waiting for favourable reply.

What I have tried:

C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
using Microsoft.Office;

namespace WinForm
{
    public partial class Form1 : Form
    {
        public string country = string.Empty;
        public Excel.Application xlApp = null;
        public Excel.Workbook XLWB = null;
        public Excel.Worksheet wsht = null;
        int IdxCurr = 0;
        int IdxPrev = 0;
        string colLineNoToPrint;

        public Form1()
        {
            InitializeComponent();
          
        }

        private void button1_Click(object sender, EventArgs e)
        {
            country = comboBox1.SelectedItem.ToString();
            DataTable boundTable = new DataTable();
            DataTable dtRefColumn = RefColumn();
            if (!string.IsNullOrEmpty(country))
            {

                IEnumerable<DataRow> query = from customer in dtRefColumn.AsEnumerable()
                                where customer.Field<string>("Country_Name") == country
                                select customer;
             

                boundTable = query.CopyToDataTable<DataRow>();
            }
            else
            {

            }

            DataTable dtMaster = dtMasterData();

            //print data to output template according to reference column
            SaveToExcel(dtMaster, dtRefColumn, country);

         
        }

        public void SaveToExcel(DataTable dtMaster, DataTable dtReftable, string country)
        {
            xlApp = new Excel.Application();
            xlApp.Workbooks.Add(true);
            wsht = xlApp.Worksheets.Add();
            wsht.Name = "S2";

            if (dtMaster.Rows.Count > 0)
            {
                for (int i = 0; i < dtMaster.Rows.Count; i++)
                {

                         //************* Struggling to print rows from here ****************
                         DataView dv = new DataView(dtMaster);

                         DataTable dt = dv.ToTable(true, dtMaster.Columns[i].ToString());

                        //Get Column Name
                        string colname = dtMaster.Columns[i].ToString();
                        //Get Reference column 
                        string RefCol = (dtReftable.AsEnumerable().Where(p => p.Field<string>("Country_Name") == country && p.Field<string>("Column_Name") == colname).Select(p => p.Field<string>("Excel_column"))).FirstOrDefault();
                        int TotRows = dtMaster.Rows.Count;
                        TotRows = 12 + TotRows;

                       
                       //To Print : Excel rows Should start to print from Rows 10
                        wsht.Cells[i][10] = dt.Rows[i].ToString();
                       //************* Struggling to print rows from here ****************
                  
                }
            }
            xlApp.Visible = true;
            xlApp.ActiveWorkbook.SaveAs(@"C:\Users\CompUMZ1A\Desktop\test.xlsx");
            xlApp.Quit();
        }

        public static DataTable dtMasterData()
        {

                DataTable tblData = new DataTable();
                tblData.Columns.Add("Prod_ID", typeof(string));
                tblData.Columns.Add("Prod_Name", typeof(string));
                tblData.Columns.Add("Prod_Quantity", typeof(string));
                tblData.Columns.Add("Prod_Expiry", typeof(string));
                tblData.Columns.Add("Prod_Manf_Date", typeof(string));
                tblData.Columns.Add("Prod_Region", typeof(string));
                tblData.Columns.Add("Prod_Head", typeof(string));
                tblData.Rows.Add("2020-1A", "Horlicks", "5000", "10-Jun-20", "05-Jan-20", "NewYork", "Sharuk");
                tblData.Rows.Add("2020-1B", "VIVA", "2000", "10-Jun-20", "05-Jan-20", "California", "Amit");
                tblData.Rows.Add("2020-1C", "Complan", "30000", "10-Jun-20", "05-Jan-20", "Mexico", "John");
                tblData.Rows.Add("2020-1D", "Bournvita", "10000", "10-Jun-20", "05-Jan-20", "NewJersy", "Rauf");

                return tblData;
          
        }


        public static DataTable RefColumn()
        {
            DataTable dataTable = new DataTable();
            dataTable.Columns.Add("Column_ID", typeof(string));
            dataTable.Columns.Add("Column_Name", typeof(string));
            dataTable.Columns.Add("Excel_column", typeof(string));
            dataTable.Columns.Add("Country_Name", typeof(string));
            dataTable.Columns.Add("Status", typeof(string));
            dataTable.Rows.Add("Prod_ID", "Prod.No", "H", "USA", "Active");
            dataTable.Rows.Add("Prod_Name", "Prod.Name", "A", "USA", "Active");
            dataTable.Rows.Add("Prod_Quantity", "Quantity", "C", "USA", "Active");
            dataTable.Rows.Add("Prod_Expiry", "Expiry Date", "D", "USA", "Active");
            dataTable.Rows.Add("Prod_Manf_Date", "Manufacturing Date", "E", "USA", "Active");
            dataTable.Rows.Add("Prod_Region", "Region", "B", "USA", "Active");
            dataTable.Rows.Add("Prod_Head", "Head of Region", "G", "USA", "Active");
            dataTable.Rows.Add("Prod_ID", "Prod. No", "B", "UK", "Active");
            dataTable.Rows.Add("Prod_Name", "Prod. Name", "A", "UK", "Active");
            dataTable.Rows.Add("Prod_Quantity", "Quantity", "X", "UK", "Active");
            dataTable.Rows.Add("Prod_Expiry", "Expiry Date", "M", "UK", "Active");
            dataTable.Rows.Add("Prod_Manf_Date", "Manufacturing Date", "N", "UK", "Active");
            dataTable.Rows.Add("Prod_Region", "Region", "O", "UK", "Active");
            dataTable.Rows.Add("Prod_Head", "Head of Region", "K", "UK", "Active");
            dataTable.Rows.Add("Prod_ID", "Prod. No", "A", "INDIA", "Active");
            dataTable.Rows.Add("Prod_Name", "Prod. Name", "B", "INDIA", "Active");
            dataTable.Rows.Add("Prod_Quantity", "Quantity", "C", "INDIA", "Active");
            dataTable.Rows.Add("Prod_Expiry", "Expiry Date", "D", "INDIA", "Active");
            dataTable.Rows.Add("Prod_Manf_Date", "Manufacturing Date", "E", "INDIA", "Active");
            dataTable.Rows.Add("Prod_Region", "Region", "F", "INDIA", "Active");
            dataTable.Rows.Add("Prod_Head", "Head of Region", "F", "INDIA", "Active");

            return dataTable;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            comboBox1.Items.Add("USA");
            comboBox1.Items.Add("UK");
            comboBox1.Items.Add("INDIA");
        }
    }
}
Posted
Updated 22-Jan-20 22:18pm
v2
Comments
Richard MacCutchan 23-Jan-20 4:34am    
You are using the index variable i to index through the rows, but also to select particular columns.
Richard MacCutchan 23-Jan-20 4:35am    
int TotRows = dtMaster.Rows.Count;
TotRows = 12 + TotRows;

What is the purpose of these two lines?
gani7787 23-Jan-20 6:16am    
int TotRows = dtMaster.Rows.Count; ==> This will count total number of data rows. ==> I think, this is not required.
TotRows = 12 + TotRows; ==> I want to print the data from Row no : 12

You can remove the above two steps also.

The aim is, data table values should start print from row.no:12 in the appropriate columns....
Richard MacCutchan 23-Jan-20 7:16am    
But it makes no sense because you do not do anything with that value, and why do you need to recalculate it every iteration of the loop?

And here are another two that do not need to be recalculated each time:
DataView dv = new DataView(dtMaster);
DataTable dt = dv.ToTable(true, dtMaster.Columns[i].ToString());

And the second line again is using the rows variable to access a column.
gani7787 23-Jan-20 23:28pm    
ok.i understood..can you pls. suggest me how to print in particular column values...?

1 solution

Please change your code in SaveToExcel:

C#
if (dtMaster.Rows.Count > 0)
            {
                for (int i = 0; i < dtMaster.Rows.Count-1; i++)
                {

                    //************* Struggling to print rows from here ****************
                    DataView dv = new DataView(dtMaster);

                    DataTable dt = dv.ToTable(true, dtMaster.Columns[i].ToString());

                    //Get Column Name
                    string colname = dtMaster.Columns[i].ToString();
                    //Get Reference column 
                    string RefCol = (dtReftable.AsEnumerable().Where(p => p.Field<string>("Country_Name") == country && p.Field<string>("Column_Name") == colname).Select(p => p.Field<string>("Excel_column"))).FirstOrDefault();
                    int TotRows = dtMaster.Rows.Count;
                    TotRows = 12 + TotRows;


                    //To Print : Excel rows Should start to print from Rows 10
                    var tmp = dt.Rows[i][0].ToString();
                    wsht.Cells[10,i+1] = tmp;
                    //************* Struggling to print rows from here ****************

                }
            }
 
Share this answer
 
Comments
gani7787 23-Jan-20 5:56am    
Thanks for your help...

getting error in the line as below

var tmp = dt.Rows[i][0].ToString();

Error : An unhandled exception of type 'System.IndexOutOfRangeException' occurred in System.Data.dll

Additional information: There is no row at position 3.

Ps : Can i print all the column values in the approriate excel column..?

pls. refer below screen shot for your reference.

https://1drv.ms/u/s!AiSRcgO5FUmNdcjWYVAuQiC8yuY?e=Y5fbJh
Kraule 23-Jan-20 10:54am    
Change the foreach-clause to:
for (int i = 0; i < dtMaster.Rows.Count-1; i++)
gani7787 23-Jan-20 23:30pm    
Dear All,
pls. give us the correct direction to follow and print the data table values in appropriate cells in excel column based on my reference table...

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