Tomas Sundberg

Tomas Sundberg

  • NA
  • 7
  • 667

Need help to create a fixed width file

May 12 2023 12:45 PM

I'm building a program that converts a .xlsx-file to a fixed width file.

I'm very new at this so it goes very slow.

I want to take the data from a DataTable and then create a fixed width file.
I was able to get the first part to work, getting the data to datatable, but i am stuck with creating the file.

The table looks like this:

I want the file to look like this:

KOH  A     123                 B
KOL
KOHF
KOR  77410-100
KOR  20090-350
KOR  56305
KOH  A     321                 B
KOL
KOHF
KOR  74016
KOR  72616-15

But with the code i've done so far the file looks like this (And repeats):

KOH  A     123                 B
KOL
KOHF
KOR  77410-100
KOR  20090-350
KOR      56305
KOR      74016
KOR   72616-15
KOR           
KOR           
KOR           
KOR           
KOR           
KOH  A     123                 B
KOL
KOHF
KOR  77410-100
KOR  20090-350
KOR      56305
KOR      74016
KOR   72616-15

This is the code:

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DataRow dr = dt.Rows[i];

                sfw.WriteLine("KOH" + "A".PadLeft(3).PadRight(8) + dr["Column1"].ToString().PadRight(6) + "B".PadLeft(15));

                sfw.WriteLine("KOL");
                sfw.WriteLine("KOHF");

                for (int r = 0; r < dt.Rows.Count; r++)
                {
                    DataRow drow = dt.Rows[r];
                    sfw.WriteLine("KOR" + drow["Column2"].ToString().PadLeft(11));
                }
            }

            sfw.Close();

Can anyone help me with this?


Answers (4)