Thursday, July 16, 2015

Reading text file with multiple headings in c#

In this article i will describe how to read a text file having certain heading line by line and fill those in data table. As we know we all deal will different types of reports may be its transaction report,balance sheet,Income expense statements,etc.All these reports have certain fixed format .Most of the reports have headers for each category of transactions.

Q1 Expenses
Q1 % Total
Q2 Expenses
Q2 % Total
Q3 Expenses
Q3 % Total
Q4 Expenses
Q4 % Total
Advertising
Print
$10,000
11.60%
$12,000
12.40%
$10,000
11.60%
$12,000
12.40%
Radio
10,000
11.60%
11,000
11.30%
10,000
11.60%
11,000
11.30%
Television
25,000
29.10%
28,000
28.90%
25,000
29.10%
28,000
28.90%
Direct Mail
30,000
34.90%
32,000
33.00%
30,000
34.90%
32,000
33.00%
Point of Purchase
5,000
5.80%
6,000
6.20%
5,000
5.80%
6,000
6.20%
Co-op
5,000
5.80%
7,000
7.20%
5,000
5.80%
7,000
7.20%
Other
1,000
1.20%
1,000
1.00%
1,000
1.20%
1,000
1.00%
Totals
$86,000
12.00%
$97,000
13.10%
$86,000
12.00%
$97,000
13.10%
Sales Promotion
Trade Shows
$2,000
15.40%
$3,000
54.50%
$2,000
15.40%
$3,000
54.50%
Sales Force Promotion
10,000
76.90%
2,000
36.40%
10,000
76.90%
2,000
36.40%
Other
1,000
7.70%
500
9.10%
1,000
7.70%
500
9.10%
Totals
$13,000
1.80%
$5,500
0.70%
$13,000
1.80%
$5,500
0.70%

Now here is the code to fill data table with such type of data and show it in gridview. Later we can fill these data in database.
using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class ReadTextFile : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void btnRead_Click(object sender, EventArgs e) { gridbind(); } protected void gridbind() { DataTable dt = new DataTable(); string path = Server.MapPath("~/Marketing.txt"); if (!string.IsNullOrEmpty(path)) { string[] readText = File.ReadAllLines(path); List<string> rows = readText.ToList<string>(); DataColumn dc; string [] headers=rows[0].Split(new string[]{ "," },StringSplitOptions.None); foreach (string s in headers) { dc = new DataColumn(s, typeof(System.String)); dt.Columns.Add(dc); } rows.RemoveAt(0); rows.RemoveAll(u => !u.Contains("\"")); rows.RemoveAll(u => u.Contains("Totals")); DataRow dr; foreach (string s in rows) { string[] values = s.Split(new string[] { "\"" }, StringSplitOptions.None); dr = dt.NewRow(); for (int i = 0; i < headers.Count(); i++) { dr[i] = values[i].Replace(",", ""); } dt.Rows.Add(dr); } } grdData.DataSource = dt; grdData.DataBind(); } }

No comments :

Post a Comment