I need to use an existing Excel file that contain macros, i need to write some data, activate some macros then read the result from the excel file from my UWP application. I
Actually using a third party library like syncfusion to implement this may be a good way. As you avoid any library that you may need to write a library by yourself since as far as I known currently there is no open library according to this thread.
The excel file format .xlsx
could be a .zip
package that you should be able to decompression it and you will find a lot of .xml
format files inside the folder. In uwp we have APIs for reading the xml files. So you can do reading and writing manipulation with these xml files.
For how to decompression a file in uwp app you should be able use ZipArchive class. For example decompression an excel file and getting one sheet may be as follows:
private async void btnopenfile_Click(object sender, RoutedEventArgs e)
{
FileOpenPicker opener = new FileOpenPicker();
opener.ViewMode = PickerViewMode.Thumbnail;
opener.FileTypeFilter.Add(".xlsx");
opener.FileTypeFilter.Add(".xlsm");
StorageFile file = await opener.PickSingleFileAsync();
if (file != null)
{
using (var fileStream = await file.OpenReadAsync())
{
using (ZipArchive archive = new ZipArchive(fileStream.AsStream(), ZipArchiveMode.Read))
{
worksheet = this.GetSheet(archive, "sheet1");
}
}
}
}
private XmlDocument GetSheet(ZipArchive archive, string sheetName)
{
XmlDocument sheet = new XmlDocument();
ZipArchiveEntry archiveEntry = archive.GetEntry("xl/worksheets/" + sheetName + ".xml");
using (var archiveEntryStream = archiveEntry.Open())
{
using (StreamReader reader = new StreamReader(archiveEntryStream))
{
string xml = reader.ReadToEnd();
txtresult.Text = xml;
sheet.LoadXml(xml);
}
}
return sheet;
}
For how to read and write xml files you can reference the XmlDocument official sample. For example you may need read one node by code as follows(This method is not directly read the value in the sheet but the value address):
private string ReadCell(XmlDocument worksheet, string cellAddress)
{
string value = string.Empty;
XmlElement row = worksheet.SelectSingleNodeNS("//x:c[@r='" + cellAddress + "']", "xmlns:x=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\"") as XmlElement;
if (row != null)
{
value = row.InnerText;
}
return value;
}
There is a complete reading sample on this thread you can reference. More detail features please develop by yourself.