我试图异步读取给定工作簿的所有Excel工作表,但是它似乎并没有发生。我的想法是在每个Excel工作表中对前123个单元格求和,并在最后打印出来。代码编译并运行没有错误,但它没有读取所有的工作表,因为使用了 async
。
namespace SyncAndAsync
{
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Excel = Microsoft.Office.Interop.Excel;
class Startup
{
static void Main()
{
string filePath = @"C:\Users\Desktop\Sample.xlsx";
Excel.Application excel = new Excel.Application();
excel.Visible = true;
excel.EnableAnimations = false;
Excel.Workbook wkb = Open(excel, filePath);
var calculation = CalculateAllWorksheetsAsync(wkb);
//foreach (var item in calculation)
//{
// Console.WriteLine(item);
//}
excel.EnableAnimations = true;
wkb.Close(true);
excel.Quit();
}
static async Task<List<Information>> CalculateAllWorksheetsAsync(Excel.Workbook wkb)
{
List<Task<Information>> tasks = new List<Task<Information>>();
foreach (Excel.Worksheet wks in wkb.Worksheets)
{
Task.Run(() => CalculateSingleWorksheetAsync(wks));
}
var results = await Task.WhenAll(tasks);
return new List<Information>(results);
}
static async Task<Information> CalculateSingleWorksheetAsync(Excel.Worksheet wks)
{
Information output = new Information();
int result = 0;
await Task.Run(() =>
{
for (int i = 1; i <= 123; i++)
{
result += (int)(wks.Cells[i, 1].Value);
}
});
output.WorksheetName = wks.Name;
output.WorksheetSum = result;
Console.WriteLine($"{wks.Name} - {result}");
return output;
}
static Excel.Workbook Open(Excel.Application excelInstance,
string fileName, bool readOnly = false,
bool editable = true, bool updateLinks = true)
{
Excel.Workbook book = excelInstance.Workbooks.Open(
fileName, updateLinks, readOnly,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, editable, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing);
return book;
}
}
}
添加了 Information
类来使用任务,可能可以跳过:
namespace SyncAndAsync
{
class Information
{
public string WorksheetName { get; set; } = "";
public int WorksheetSum { get; set; } = 0;
}
}
依赖项:
- 需要添加引用
Microsoft.Office.Interop.Excel
; - 将
string filePath = @"C:\Users\Desktop\Sample.xlsx";
更改为相关内容,并确保在Excel文件的每个工作表中第一列都有一些数字,以获取结果;
问题 - 如何使异步运行并显示所有工作表的总和?
Main()
改成异步的,而我一直在避免这样做(原因未知)。 - Vityata