Reputation: 312
I have a UWP app. I have taken an excel file off of my SharePoint drive, changed it to a byte array, and saved it to my hard drive.
So I realized at this point that I already had the file open, so there was no need to open it again. So I made some modifications (the entire class this time):
class FileHelper
{
public static string saveLocation;
public static SpreadsheetDocument spreadsheetDoc;
public static async void GetFileAsync()
{
var (authResult, message) = await Authentication.AquireTokenAsync();
var httpClient = new HttpClient();
HttpResponseMessage response;
var request = new HttpRequestMessage(HttpMethod.Get, MainPage.fileurl);
request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", authResult.AccessToken);
response = await httpClient.SendAsync(request);
byte[] fileBytes = await response.Content.ReadAsByteArrayAsync();
StorageLibrary videoLibrary = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Videos);
string saveFolder = videoLibrary.SaveFolder.Path;
string saveFileName = App.Date + "-" + App.StartTime + "-" + App.IBX + "-" + App.Generator + ".xlsx";
saveLocation = saveFolder + "\\" + saveFileName;
using (MemoryStream stream = new MemoryStream())
{
stream.Write(fileBytes, 0, (int)fileBytes.Length);
using (spreadsheetDoc = SpreadsheetDocument.Open(stream, true))
{
UpdateCell(spreadsheetDoc, App.Date, 2, "D");
await Task.Run(() =>
{
File.WriteAllBytes(saveLocation, stream.ToArray());
});
}
}
}
public static void UpdateCell(SpreadsheetDocument docName, string text,
uint rowIndex, string columnName)
{
WorksheetPart worksheetPart =
GetWorksheetPartByName(spreadsheetDoc, "GenRun");
if (worksheetPart != null)
{
Cell cell = GetCell(worksheetPart.Worksheet,
columnName, rowIndex);
cell.CellValue = new CellValue(text);
cell.DataType =
new EnumValue<CellValues>(CellValues.String);
}
}
private static WorksheetPart
GetWorksheetPartByName(SpreadsheetDocument document,
string sheetName)
{
IEnumerable<Sheet> sheets =
document.WorkbookPart.Workbook.GetFirstChild<Sheets>().
Elements<Sheet>().Where(s => s.Name == sheetName);
if (sheets.Count() == 0)
{
return null;
}
string relationshipId = sheets.First().Id.Value;
WorksheetPart worksheetPart = (WorksheetPart)
document.WorkbookPart.GetPartById(relationshipId);
return worksheetPart;
}
private static Cell GetCell(Worksheet worksheet,
string columnName, uint rowIndex)
{
Row row = GetRow(worksheet, rowIndex);
if (row == null)
return null;
return row.Elements<Cell>().Where(c => string.Compare
(c.CellReference.Value, columnName +
rowIndex, true) == 0).First();
}
private static Row GetRow(Worksheet worksheet, uint rowIndex)
{
return worksheet.GetFirstChild<SheetData>().
Elements<Row>().Where(r => r.RowIndex == rowIndex).First();
}
}
Writes the file but does not update the file with the data input called for by UpdateCell().
Upvotes: 0
Views: 268
Reputation: 312
OK....This is what I ended up with. It's probably not pretty, but it worked.
First I changed the click event to separate the updates from the transfer of the template file.
private async void FileButton_Click(object sender, RoutedEventArgs e)
{
await FileHelper.GetFileAsync();
await FileHelper.UpdateCell(FileHelper.saveLocation, App.Date, 2, "D");
await FileHelper.UpdateCell(FileHelper.saveLocation, App.Maximo, 3, "D");
...
await FileHelper.UpdateCell(FileHelper.saveLocation, App.StopHours, 26, "J");
}
Then I updated both the GetFileAsync() and UpdateCell() to a Task instead of a void. Then, when I got the the await Task.Run I added a return TaskStatus.RanToCompletion.
class FileHelper
{
public static string saveLocation;
public static SpreadsheetDocument spreadsheetDoc;
public static async Task GetFileAsync()
{
var (authResult, message) = await Authentication.AquireTokenAsync();
var httpClient = new HttpClient();
HttpResponseMessage response;
var request = new HttpRequestMessage(HttpMethod.Get, MainPage.fileurl);
request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", authResult.AccessToken);
response = await httpClient.SendAsync(request);
byte[] fileBytes = await response.Content.ReadAsByteArrayAsync();
StorageLibrary videoLibrary = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Videos);
string saveFolder = videoLibrary.SaveFolder.Path;
string saveFileName = App.Date + "-" + App.StartTime + "-" + App.IBX + "-" + App.Generator + ".xlsx";
saveLocation = saveFolder + "\\" + saveFileName;
using (MemoryStream stream = new MemoryStream())
{
stream.Write(fileBytes, 0, (int)fileBytes.Length);
using (spreadsheetDoc = SpreadsheetDocument.Open(stream, true))
{
await Task.Run(() =>
{
File.WriteAllBytes(saveLocation, stream.ToArray());
return TaskStatus.RanToCompletion;
});
}
}
}
public async static Task UpdateCell(string docName, string text,
uint rowIndex, string columnName)
{
StorageLibrary videoLibrary = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Videos);
string saveFolder = videoLibrary.SaveFolder.Path;
string saveFileName = App.Date + "-" + App.StartTime + "-" + App.IBX + "-" + App.Generator + ".xlsx";
saveLocation = saveFolder + "\\" + saveFileName;
await Task.Run(() =>
{
using (spreadsheetDoc = SpreadsheetDocument.Open(saveLocation, true))
{
WorksheetPart worksheetPart =
GetWorksheetPartByName(spreadsheetDoc, "GenRun");
if (worksheetPart != null)
{
Cell cell = GetCell(worksheetPart.Worksheet,
columnName, rowIndex);
cell.CellValue = new CellValue(text);
cell.DataType =
new EnumValue<CellValues>(CellValues.String);
worksheetPart.Worksheet.Save();
}
}
return TaskStatus.RanToCompletion;
});
}
private static WorksheetPart
GetWorksheetPartByName(SpreadsheetDocument document,
string sheetName)
{
IEnumerable<Sheet> sheets =
document.WorkbookPart.Workbook.GetFirstChild<Sheets>().
Elements<Sheet>().Where(s => s.Name == sheetName);
if (sheets.Count() == 0)
{
return null;
}
string relationshipId = sheets.First().Id.Value;
WorksheetPart worksheetPart = (WorksheetPart)
document.WorkbookPart.GetPartById(relationshipId);
return worksheetPart;
}
private static Cell GetCell(Worksheet worksheet,
string columnName, uint rowIndex)
{
Row row = GetRow(worksheet, rowIndex);
if (row == null)
return null;
return row.Elements<Cell>().Where(c => string.Compare
(c.CellReference.Value, columnName +
rowIndex, true) == 0).First();
}
private static Row GetRow(Worksheet worksheet, uint rowIndex)
{
return worksheet.GetFirstChild<SheetData>().
Elements<Row>().Where(r => r.RowIndex == rowIndex).First();
}
}
Upvotes: 0