I want to save one column from my .xls file into .txt file using C#. The column of .xls file contain the City name of a country. So far What I did, I extract the city name which contain the population upper than 20000. Now I want to store only the City name not the population with newline order in a text file. But When I try to save it stores as blank text file. Here is my code to extract data from. xls file.
public class City
{
public DataTable DataService()
{
var data = new DataTable();
var startPath = Application.StartupPath;
string folderName = Path.Combine(startPath, "CityList");
System.IO.Directory.CreateDirectory(folderName);
string SavedfileName = "POI_list.txt";
var Saving_path = Path.Combine(folderName, SavedfileName);
string fileName = "Zensus_Gemeinden_org.xlsx";
var path = Path.Combine(startPath, fileName);
String name = "Gemeinden_31.12.2011_Vergleich";
String constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
path + ";Extended Properties='Excel 12.0 XML;HDR=YES;';";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand oconn = new OleDbCommand("Select [3] as City,[4] as Population, * From [" + name + "$D7:E11300] Where [4] > 20000", con);
//con.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
sda.Fill(data);
//string Place_Json = "Place_List:" + JsonConvert.SerializeObject(data, Formatting.Indented);
File.WriteAllText(Saving_path, data.ToString()); // it stores as blank text file
return data;
}
}
Modify: Now I am trying in this way. But there shows error athat sb does not exist in the current folder
sda.Fill(data);
foreach(DataRow r in data.Rows)
{
string output= sb.append(r["City"] + "\n");
File.WriteAllText(Saving_path, data);
}
New Modification:
var sb = new StringBuilder();
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
foreach(DataRow r in dt.Rows)
{
sb.Appent(r["City"] + "\n");
}
File.WriteAllText(Saving_path,sb.ToString());
return dt;
}
I got My .txt file in this way
Flensburg Kiel Lübeck Neumünster Heide Geesthacht.....