我正在处理的应用程序必须获取保存在 excel 中的每个链接并运行它,如果页面状态为 404,我必须将每个链接保存在新的 excel 中(我的意思是在 excel 中是全部,而不是每个链接在一个单独的 excel 中)。到目前为止,我已经设法让每个链接都运行起来,并创建了一个新的 excel,以防我设法让它工作,但不幸的是,我被困在这一点上,我不知道如何或写什么检查现有 Excel 中的 URL 后,每次状态为 404 时保存的代码
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Office.Interop.Excel;
using OfficeOpenXml;
namespace StartaproUrls
{
partial class Program
{
private static int statusCode;
private static HttpResponseMessage result;
private static object[,] valueArray;
static async Task Main(string[] args)
{
using var client = new HttpClient();
string path = @"C:\Users\stefanv\Downloads\startapro_urls.xlsx";
Application excelApp = new();
if (excelApp != null)
{
Workbook excelWorkbook = excelApp.Workbooks.Open(path);
Worksheet excelWorksheet = (Worksheet)excelWorkbook.Sheets[1];
Microsoft.Office.Interop.Excel.Range excelRange = excelWorksheet.UsedRange;
int rowCount = excelRange.Rows.Count;
int colCount = excelRange.Columns.Count;
valueArray = (object[,])excelRange.get_Value(
XlRangeValueDataType.xlRangeValueDefault);
for (int i = 1; i <= 20; i++)
{
for (int j = 1; j <= colCount; j++)
{
result = await client.SendAsync(new HttpRequestMessage(HttpMethod.Head, $"https://beta.startapro.hu{valueArray[i, j]}"));
statusCode = (int)result.StatusCode;
Console.WriteLine(statusCode); // or result
}
}
excelWorkbook.Close();
excelApp.Quit();
}
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
var file = new FileInfo(@"C:\Users\stefanv\Downloads\startapro_urlsError.xlsx");
var urlError = GetSetupData();
await CreateExcelForErrorUrls.SaveExcelFile(urlError, file);
}
public static List<UrlErrorModel> GetSetupData()
{
List<UrlErrorModel> output = new()
{
new() { UrlWithError = valueArray }
};
return output;
}
}
}
Bellow 是用于创建 Excel 的类
using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static StartaproUrls.Program;
namespace StartaproUrls
{
class CreateExcelForErrorUrls
{
public static async Task SaveExcelFile(List<UrlErrorModel> urlError, FileInfo file)
{
DeleteIFExists(file);
using var package = new ExcelPackage(file);
var ws = package.Workbook.Worksheets.Add("ErrorRaport");
var range = ws.Cells["A1"].LoadFromCollection(urlError, true);
range.AutoFitColumns();
await package.SaveAsync();
}
private static void DeleteIFExists(FileInfo file)
{
if (file.Exists)
{
file.Delete();
}
}
}
}
Bellow 是 UrlError 的模型
namespace StartaproUrls
{
partial class Program
{
public class UrlErrorModel
{
public object UrlWithError { get; set; }
}
}
}