【发布时间】:2017-06-27 19:30:59
【问题描述】:
我能够正确打开和读取 excel 文件,但是输出不会停止。当有空单元格时,它会继续运行。一旦程序到达没有数据的单元格,如何让程序停止?
我已阅读其他帖子并尝试过this 帖子,因为解决方案有点相似。代码有什么问题?
感谢您的帮助
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
{
private static int colCount;
private static int rowCount;
static void Main(string[] args)
{
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(@"C:\File.xlsx");
Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
Excel.Range xlRange = xlWorksheet.UsedRange;
int rowCount = xlWorksheet.Rows.Count;
int colCount = xlWorksheet.Columns.Count;
for (int i = 1; i <= rowCount; i++)
{
for (int j = 1; j <= colCount; j++)
{
//new line
if (j == 1)
{
Console.Write("\r\n");
}
//write the value to the console
if (xlWorksheet.Cells[i, j].Value2 != null)
{
Console.Write(xlRange.Cells[i, j].Value2.ToString() + "\t");
}
}
}
//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
xlWorkbook.Close();
Marshal.ReleaseComObject(xlWorkbook);
//quit and release
xlApp.Quit();
Marshal.ReleaseComObject(xlApp);
}
} }
【问题讨论】:
-
xlRange.Rows.Count 而不是 xlWorksheet.Rows.Count
-
@Slai,试过了。仍然做同样的事情。
-
find the last used cell 的方法有很多种,但也取决于你之后做什么。如果您只想要制表符分隔的字符串中的数据,您可以
xlWorksheet.Cells.Copy并从剪贴板中获取文本。