开发者

Read in xls file as well as current csv file in app

开发者 https://www.devze.com 2023-02-18 19:33 出处:网络
I have the following code - private void button1_Click(object sender, EventArgs e) { string csv = File.ReadAllText(\"FilePath\");

I have the following code -

private void button1_Click(object sender, EventArgs e)
    {
        string csv = File.ReadAllText("FilePath");

        WebService.function res = new WebService.function();

        XDocument doc = ConvertCsvToXML(csv, new[] { "," });

I was wondering how a could adjust the code so that it not only reads .csv files but also .xls files?

I created a public XDocument to do this -

public  XDocument ConvertCsvToXML(string csvString, string[] separatorField)
    {
        var sep = new[] { "\n" };
      开发者_开发知识库  string[] rows = csvString.Split(sep, StringSplitOptions.RemoveEmptyEntries);

        var xsurvey = new XDocument(
        new XDeclaration("1.0", "UTF-8", "yes"));
        var xroot = new XElement("details"); 


If I understand your question correctly, you are looking to parse an excel file as text in the same manner that you parse the csv file. While this is possible, you should consider using Office Interop interfaces to do this. If you want to parse the raw file you'll need to account for the different formats between Office versions and a whole slew of encoding/serialization tasks; no small task.

Here are some resources to get you started:

  1. Reading Excel from C#
  2. How to Automate Excel from C#


I'm not sure from your question...but if you are asking how to read an excel file in c#, this will work:

string fileName = [insert path and name];
string connectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;data source={0}; Extended Properties=Excel 8.0;", fileName);   // Create the data adapter pointing to the spreadsheet 
var oa = new OleDbDataAdapter("SELECT * FROM [xxx$]", connectionString); // xxx is tab name
// Create a blank data set 
var ds = new DataSet();    // Fill the data set using the adapter 
oa.Fill(ds, "table1");    // Create a data table from the data set 
DataTable dt1 = ds.Tables["table1"];
foreach (DataRow dr in dt1.Rows)
{
   ...
}
0

精彩评论

暂无评论...
验证码 换一张
取 消