【问题标题】:Looping through each cell in excel/csv sheet [duplicate]循环遍历excel / csv表中的每个单元格[重复]
【发布时间】:2017-06-30 02:14:16
【问题描述】:

这个问题与我的上一篇文章(link)有关。我想遍历每个单元格,以便我可以清理我的非 ascii 值表(函数 ReturnCleanASCII )用于此目的。但是,当我通过单元格时,我得到一个空值。

代码

foreach (Excel.Range range in xlRange.Cells){
          Console.WriteLine(range.Value2.ToString());
}

我正在使用上面的代码遍历每个单元格。这是遍历每个单元格的错误方式吗?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using Excel = Microsoft.Office.Interop.Excel;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Excel.Application xlApp = new Excel.Application();
            Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(@"C:\Users\username\Desktop\Error Records.csv");
            Excel.Worksheet xlWorksheet = xlWorkbook.Sheets[1];
            Excel.Range xlRange = xlWorksheet.UsedRange;

            int lastUsedRow = xlWorksheet.Cells.Find("*", System.Reflection.Missing.Value,
                System.Reflection.Missing.Value, System.Reflection.Missing.Value,
                Excel.XlSearchOrder.xlByRows, Excel.XlSearchDirection.xlPrevious,
                false, System.Reflection.Missing.Value, System.Reflection.Missing.Value).Row;

            int lastUsedColumn = xlWorksheet.Cells.Find("*", System.Reflection.Missing.Value,
                System.Reflection.Missing.Value, System.Reflection.Missing.Value,
                Excel.XlSearchOrder.xlByColumns, Excel.XlSearchDirection.xlPrevious,
                false, System.Reflection.Missing.Value, System.Reflection.Missing.Value).Column;

            int lastColumnCount = lastUsedColumn;



            for (int i = 1; i <= lastUsedColumn; i++)
            {
                for (int j = 1; j <= lastUsedRow; j++)
                {
                    xlWorksheet.Cells[j, (lastColumnCount + 1)] = "Testing data 134";
                }
            }

            foreach (Excel.Range range in xlRange.Cells)
            {
                Console.WriteLine(range.Value2.ToString());
            }


            xlWorksheet.Cells[1, (lastUsedColumn + 1)] = "Title";
            xlWorkbook.Save();
            //cleanup
            GC.Collect();
            GC.WaitForPendingFinalizers();

            //rule of thumb for releasing com objects:
            //  never use two dots, all COM objects must be referenced and released individually
            //  ex: [somthing].[something].[something] is bad

            //release com objects to fully kill excel process from running in the background
            Marshal.ReleaseComObject(xlRange);
            Marshal.ReleaseComObject(xlWorksheet);

            //close and release
            var data = ReturnCleanASCII(xlWorksheet.ToString());
            xlWorkbook.SaveAs("C:\\Users\\username\\Desktop\\Errors_four.csv".Trim(), Excel.XlFileFormat.xlCSV);
            xlWorkbook.Close();
            Marshal.ReleaseComObject(xlWorkbook);

            //quit and release
            xlApp.Quit();
            Marshal.ReleaseComObject(xlApp);

        }

        public static string ReturnCleanASCII(string s)
        {
            StringBuilder sb = new StringBuilder(s.Length);
            foreach (char c in s.ToCharArray())
            {
                if ((int)c > 127) // you probably don't want 127 either
                    continue;
                if ((int)c < 32)  // I bet you don't want control characters 
                    continue;
                if (c == ',')
                    continue;
                if (c == '"')
                    continue;
                sb.Append(c);
            }
            return sb.ToString();
        }
    }
}

错误:

无法对空引用执行运行时绑定

堆栈跟踪:

   at CallSite.Target(Closure , CallSite , Object )
   at System.Dynamic.UpdateDelegates.UpdateAndExecute1[T0,TRet](CallSite site, T0 arg0)
   at CallSite.Target(Closure , CallSite , Object )
   at ConsoleApplication1.Program.Main(String[] args) in C:\Users\username\documents\visual studio 2015\Projects\ConsoleApplication1\ConsoleApplication1\Program.cs:line 44
   at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
   at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
   at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
   at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart()

【问题讨论】:

  • @Dai,抱歉打错标签了。
  • 堆栈跟踪告诉你什么?
  • @JoePhillips,它只读取第一行。
  • @gavsta707,是的。它在 Console.Writeline 代码上中断并出现错误无法对空引用执行运行时绑定
  • 堆栈跟踪不读取内容。他们表达了错误。如果您希望我们知道发生了什么,您需要与我们分享这一点

标签: c# .net excel


【解决方案1】:

使用Convert.ToString(range.Value2) 而不是range.Value2.ToString()

见:Cannot perform runtime binding on a null reference - Empty Excel Cells

【讨论】:

  • 我通过复制并粘贴您的错误消息然后在其中添加单词“excel”找到了这一点。这是谷歌的第一个结果。
  • 感谢您的帮助,我确实尝试过。我想我已经坚持了一段时间,所以可能错过了。
猜你喜欢
  • 2019-10-15
  • 1970-01-01
  • 1970-01-01
  • 2015-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-07
  • 2021-05-13
相关资源
最近更新 更多