Как я могу загрузить Excel в функции Azure? Я использую контейнер BLOB-объектов и приложение логики, после выполнения загружаемого кода и открытия файла (excel (.xlsx)) на своем портале Azure, но я не вижу никаких данных в своем приложении Excel и получаю эту ошибку: " Excel не может открыть файл «excel.xlsx», поскольку формат файла или расширение файла недопустимо. Убедитесь, что файл не был поврежден и что расширение файла соответствует формату файла ".
[FunctionName("Function1")]
public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]HttpRequestMessage req, TraceWriter log)
{
log.Info("C# HTTP trigger function processed a request.");
CloudStorageAccount cStorage = CloudStorageAccount.Parse(ConfigurationManager.AppSettings["ConnectionStorageAccount"]);
CloudBlobClient blobClient = cStorage.CreateCloudBlobClient();
CloudBlobContainer container = blobClient.GetContainerReference(ConfigurationManager.AppSettings["ContainerName"]);
CloudBlockBlob blob = container.GetBlockBlobReference("excel.xlsx");
DataSet ds;
using (var memoryStream = new MemoryStream())
{
blob.DownloadToStream(memoryStream);
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(memoryStream);
ds = excelReader.AsDataSet();
excelReader.Close();
}
DataTable dt = CrearDataTable(ds);
dynamic data = await req.Content.ReadAsAsync<object>();
string nombre = req.GetQueryNameValuePairs().FirstOrDefault(parametros => string.Compare(parametros.Key, "nombre", true) == 0).Value;
string valor = req.GetQueryNameValuePairs().FirstOrDefault(parametros => string.Compare(parametros.Key, "valor", true) == 0).Value;
if (nombre != null && valor != null)
{
InsertarDatos(dt, nombre, valor);
string csv = ObtenerCSV(dt);
byte[] arrayBytes = Encoding.UTF8.GetBytes(csv);
blob.UploadFromByteArray(arrayBytes, 0, arrayBytes.Length);
return req.CreateResponse(HttpStatusCode.OK, csv);
}
else
return req.CreateResponse(HttpStatusCode.BadRequest, "Bad request");
}
private static void InsertarDatos(DataTable dt, string nombreCompleto, string valor)
{
// 1. Iteramos por todas las filas hasta encontrar el nombre objetivo
foreach(DataRow fila in dt.Rows)
{
// 2. Transformamos las tres primeras filas que equivalen a nombre, primer apellido y segundo apellido a un nombre completo
string nombre = fila[0].ToString() + " " + fila[1].ToString() + " " + fila[2].ToString();
// 3. Si ambos nombres coinciden
if (nombre.Equals(nombreCompleto))
{
// 4. Añado el valor a la fila
fila[4] = valor;
// 5. Terminamos con la iteración
break;
}
}
}
private static DataTable CrearDataTable(DataSet excelData)
{
// 0. DataTable carga los datos en memoria
DataTable dt = new DataTable();
// 1. Añadimos los nombre de las columnas
dt.Columns.Add("Nombre", typeof(string));
dt.Columns.Add("Apellido 1", typeof(string));
dt.Columns.Add("Apellido 2", typeof(string));
dt.Columns.Add("DNI / NIE", typeof(string));
dt.Columns.Add("Importe", typeof(string));
// 2. Añadimos a la nueva tabla el contenido de todos los campos.
excelData
.Tables[0]
.AsEnumerable()
.Skip(1)
.ToList()
.ForEach(dr => dt.Rows.Add(dr[0], dr[1], dr[2], dr[3], dr[4]));
return dt;
}
private static string ObtenerCSV(DataTable table)
{
// 1. Creamos un StringBuilder para almacenar los resultados
var result = new StringBuilder();
for (int i = 0; i < table.Columns.Count; i++)
{
result.Append(table.Columns[i].ColumnName);
result.Append(i == table.Columns.Count - 1 ? "\n" : ",");
}
foreach (DataRow row in table.Rows)
{
for (int i = 0; i < table.Columns.Count; i++)
{
result.Append(row[i].ToString());
result.Append(i == table.Columns.Count - 1 ? "\n" : ",");
}
}
return result.ToString();
}
}
}
Я ожидал правильного Excel, но получаю эту ошибку: «Excel не может открыть файл« excel.xlsx », потому что формат файла или расширение файла недопустимо. Убедитесь, что файл не был поврежден и что расширение файла соответствует формату файла "