ClosedXML Webform - foreach 循环循环两次

Posted

技术标签:

【中文标题】ClosedXML Webform - foreach 循环循环两次【英文标题】:ClosedXML Webform - foreach loop looping twice 【发布时间】:2021-10-25 12:00:01 【问题描述】:

所以我的问题是,当我尝试读取 excel 文件时,它会在 gridview 中打印正确的输出一次,但是当我尝试将 row[cells] 存储到使用 serials += row[cells] 的字符串变量中时,它是循环foreach循环两次,我不知道怎么解决!

WebForm1.aspx

WebForm1.aspx.cs

using ClosedXML.Excel;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1

public partial class WebForm1 : System.Web.UI.Page


    String serials = "";
    int sheetRowCount = 0;
    int rowCount = 0;
    int ColumnCount = 0;
    int i, rownum=0;
    protected void Page_Load(object sender, EventArgs e)
    

    

    protected void Button1_Click(object sender, EventArgs e)
    

        // checking File Extension
        if (checkFileExtension())
        

            // reading File if extension is true
            readExcelFile();

        

    

    private bool checkFileExtension()
    
        String[] allowedExtensions =  "xls", "xlsx" ;
        String ext = System.IO.Path.GetExtension(FileUpload1.PostedFile.FileName);
        bool isValidFile = false;
        for (int i = 0; i < allowedExtensions.Length; i++)
        
            if (ext == "." + allowedExtensions[i])
            
                isValidFile = true;
            
        

        if (!isValidFile)
        
            error1.Text = "Allowed FileTypes are .xls/.xlsx";
            return isValidFile;
        
        else
        
            readExcelFile();
            return isValidFile;
        
    

    private void readExcelFile()
    
        // to bind data table to gridview
        DataTable dt = new DataTable();

        // creating new workbook object and sending Uploaded File as input File
        using (XLWorkbook workbook = new XLWorkbook(FileUpload1.PostedFile.InputStream))
        
            // creating excel worksheet object to access worksheet from workbook(Excel File)
            IXLWorksheet sheet = workbook.Worksheet(1);

            // initializing 1st row
            bool firstRow = true;
            foreach (IXLRow row in sheet.Rows())
            
                sheetRowCount++;
                //System.Diagnostics.Debug.WriteLine("SHEET ROW COUNT: " + sheetRowCount);
                // printing 1st row as headers of Table DATA
                if (firstRow)
                
                    // getting cells of 1st row
                    foreach (IXLCell cell in row.Cells())
                    
                        // adding full 1st row cells into data table
                        dt.Columns.Add(cell.Value.ToString());
                    
                    // making 1st row = false as 1st is finished
                    firstRow = false;
                
                else
                
                    rowCount++;
                    rownum++;
                  
                    // as it is 2nd row it will be printed as normal text
                    // adding empty rows in sheet
                    dt.Rows.Add();

                    //System.Diagnostics.Debug.WriteLine("Rows Count : " + rowCount);
                    // variable for couting row
                    i = 0;
                    // getting cells in rows
                    foreach (IXLCell cell in row.Cells())
                    
                        // to stop Row indexer we use row count - 1 as it loops
                        // it always keep row to row - 1 to add value to corrent row
                        dt.Rows[dt.Rows.Count - 1][i] = cell.Value.ToString();
                        ColumnCount++;
                        //System.Diagnostics.Debug.WriteLine("Column Count: " + ColumnCount);
                        i++;
                    

                
                

            
        

        //System.Diagnostics.Debug.WriteLine("=====================================");
        // sheet Row Count
        //System.Diagnostics.Debug.WriteLine("SHEET ROW COUNT: " + sheetRowCount);
        sheetRowCount = 0;
        // Row Count
        ///System.Diagnostics.Debug.WriteLine("Rows Count : " + rowCount);
        rowCount = 0;

        //System.Diagnostics.Debug.WriteLine("Current Row: " + rownum);
        rownum = 0;

        //Column Count
        //System.Diagnostics.Debug.WriteLine("Current Column: " + i);
        i = 0;

        //DATA TABLE
        // setting data source to gridview
        GridView1.DataSource = dt;
        // binding data to gridview
        GridView1.DataBind();


        gettingAllSerialsIntoArrayToJSON(dt);
    

    private void gettingAllSerialsIntoArrayToJSON(DataTable dt)
    

        System.Diagnostics.Debug.WriteLine("after printing: " + dt.Rows.Count);
        // For each row, print the values of each column.
        // 2 rows  - ROW 0 -- Row 1
        for (int i = 0; i < dt.Rows.Count; i++)
        
            // 1 column
            for (int j = 0; j < dt.Columns.Count; j++)
            
                serials += i + "-" + j + " : " + dt.Rows[i][j].ToString() + "END LINE   ";
            
        

        error1.Text = serials;

    

【问题讨论】:

你能显示连续剧内容的摘录来给我们看重复吗?另外,你认为是 i 循环还是 j 循环运行了两次? 欢迎来到 Stack Overflow!请不要将解决方案公告编辑到问题中。接受(即单击旁边的“勾选”)现有答案之一,如果有的话。如果现有答案尚未涵盖您的解决方案,您还可以创建自己的答案,甚至接受它。 【参考方案1】:

我想通了!我调用 readExcel() 函数两次我的布尔函数返回 true,因为文件是 xls/xlsx 我调用 readExcel() 重复值示例

 protected void Button1_Click(object sender, EventArgs e)


    // checking File Extension
    if (checkFileExtension())
    

        // reading File if extension is true
        readExcelFile();  ===> here after checking extension I have to use function

    



private bool checkFileExtension()

    String[] allowedExtensions =  "xls", "xlsx" ;
    String ext = System.IO.Path.GetExtension(FileUpload1.PostedFile.FileName);
    bool isValidFile = false;
    for (int i = 0; i < allowedExtensions.Length; i++)
    
        if (ext == "." + allowedExtensions[i])
        
            isValidFile = true;
        
    

    if (!isValidFile)
    
        error1.Text = "Allowed FileTypes are .xls/.xlsx";
        return isValidFile;
    
    else
    
        readExcelFile();  <== this is wrong as this function is only used to return file extension validation
        return isValidFile;
    

感谢大家的帮助!

【讨论】:

很高兴听到您的问题已经解决,您可以点击“✔”将您的回复标记为答案。它还将帮助其他人解决类似的问题。 我无法勾选或编辑我的问题以添加标签 [已解决],因为我无法检查自己的答案,您能回答一下,以便我检查并使其解决 您可以通过单击“✔”将您的回复标记为答案,而无需添加[已解决]标签。这也告诉其他人你的问题已经解决了。 什么意思,你不能edit你自己的帖子?这应该是可能的。你登录了吗?

以上是关于ClosedXML Webform - foreach 循环循环两次的主要内容,如果未能解决你的问题,请参考以下文章

使用ClosedXML,读取到空行

使用 closedxml 从 web api 下载 excel 文件

csharp [cmをinchに変换] ClosedXMLで余白などの指定をするときはインチ指定しなければならない。#ClosedXML #ExtensionMethod

显示/交互/可见 ClosedXML Excel.XLWorkbook 不保存

excel的当前格式在 Closedxml SaveAs 方法中发生变化

csharp [Excel帐票] EXCELで帐票出力するときに使えるかも。#ClosedXML