使用占位符使用EPPlus库

时间:2016-07-17 22:45:29

标签: c# asp.net asp.net-mvc epplus

我正在编写一个应用程序,用户可以使用联系信息上传excel文件,其中列数不为我所知。工作表可以具有尽可能多的列和行。我想要实现的是,用户可以通过使用基于零的索引作为列的占位符来构建消息,从而向表中的每个联系人发送消息。例如,在下面的表中假设第一行表示标题{ {3}}

用户将构建他的消息,如Dear {0} {1}, your age is {2} and your email is {3},其中{0}是第一列的标题,{1}是第二列的标题,on和on就是这样。这应该将消息输出为Dear Jon Snow, your age is 27 and your email is jsnow@winterfell.com。我想为表格中的每一行执行此操作。我正在使用EPplus解析excel表。这就是我尝试过的。

static void Main(string[] args)
{
    var path = "C:\\Users\\RIDWAN\\Desktop\\ExcelFile.xlsx";
    FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);            
    using (var package = new ExcelPackage(fs))
    {
        var currentSheet = package.Workbook.Worksheets;//get the work sheet
        var workSheet = currentSheet.First();//get the first sheet
        var noOfCol = workSheet.Dimension.End.Column; //get the no of col in the active sheet
        var noOfRow = workSheet.Dimension.End.Row; /get the no of row in the active sheet
        var placeholder = "{FirstName}";
        for (int i = 2; i <= noOfRow; i++)
        {
            for (int j = 1; j <= noOfCol; j++)
            {
                var message = String.Format("Dear {0} {1}, your age is {2} and your email is {3}", workSheet.GetValue(i, j));
                Console.Write(message);
            }
        }
        Console.ReadLine();
    }

}

我想使用占位符输出格式正确的消息,以生成带有相应占位符值的消息。

1 个答案:

答案 0 :(得分:1)

似乎你只需要一个for循环,因为cols的数量是已知的 - 它的行是这里的变种。简单地做这样的事情:

using (var package = new ExcelPackage(fs))
{
    var currentSheet = package.Workbook.Worksheets;//get the work sheet
    var workSheet = currentSheet.First();//get the first sheet
    var noOfCol = workSheet.Dimension.End.Column; //get the no of col in the active sheet
    var noOfRow = workSheet.Dimension.End.Row; // get the no of row in the active sheet
    var placeholder = "{FirstName}";
    for (int i = 2; i <= noOfRow; i++)
    {
        var vals = workSheet.Cells[i, 1, i, noOfCol].Select(c => c.Value).ToArray();
        var message = String.Format("Dear {0} {1}, your age is {2} and your email is {3}", vals);
        Console.WriteLine(message);
    }
}

在输出中给出了这个int:

Dear Jon Snow, your age is 27 and your email is jsnow@winderfell.com
Dear Arya Stark, your age is 18 and your email is aryastark@winterfell.com
Dear Eddard Stark, your age is 50 and your email is lordeddard@winterfell.com