简体   繁体   中英

C# reading from and writing to an excel file

I am having issues creating a class to read and write to an excel file. I need to read in the data from the file (only one column). Then I need to search the string input for square brackets [] and/or parentheses (). If the line contains those, I need to take the information inside those and separate (split) the answers by a forward slash (/). I keep getting errors with the splitting on the variables. Could someone point me in the right direction? Thanks!

using System;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml.Linq;
using System.Text.RegularExpressions;

namespace DataExcelApp
{
    public class ExcelApp
    {
        private static void Main()
        {
            //make connection to document
            var fileName = string.Format("C:/Users/kbangert/Desktop/Karpel/ChargeLanguage.xlsx", Directory.GetCurrentDirectory());
            var connectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0; data source={0}; Extended Properties=Excel 8.0;", fileName);

            //first query to document
            var adapter = new OleDbDataAdapter("SELECT * FROM [ChargeLanguage] WHERE [description] != string.Empty", connectionString);
            var ds = new DataSet();
            adapter.Fill(ds, "descriptions");

            //DataTable data = ds.Tables["descriptions"];
            var data = ds.Tables["descript"].AsEnumerable();

            if (data != null)
            {
                var entry = data.ToString();
                var pattern = @"\[(.*?)\]";
                var matches = Regex.Matches(entry, pattern);

                foreach (Match m in matches)
                {
                    Console.WriteLine(m.Groups[1]);
                }

                string[] words = matches.Split('/');
                foreach (string word in words)
                {
                    Console.WriteLine(word);
                }
            }    

In this line

string[] words = matches.Split('/');

matches is a collection of Match objects. There's no Split method on that.

You probably want to do this:

foreach (Match m in matches)
{
    Console.WriteLine(m.Groups[1]);

     string[] words = m.Groups[1].Value.Split('/');
     foreach (string word in words)
        Console.WriteLine(word);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM