working with excel files in uwp - vb.net

my question is - I can't read data from excel file. I'm using spreadsheetgear library. I'm writing for uwp platfom (I need to show user data from excel file). may someone help?
(gv1 = gridview). or I should use other library? May be anyone already worked with spreadsheetgear and can help.
Public Async Function open_excel() As Task
Dim Values As String()
Dim filepicker As New FileOpenPicker With {.ViewMode = PickerViewMode.List, .SuggestedStartLocation = PickerLocationId.Downloads}
filepicker.FileTypeFilter.Add(".xls")
filepicker.FileTypeFilter.Add(".xlsx")
Dim storefile As StorageFile = Await filepicker.PickSingleFileAsync
Dim workbook As IWorkbook = Factory.GetWorkbook(storefile.Path)
Dim worksheet As IWorksheet = workbook.Worksheets(0)
gv1.ItemsSource = worksheet.Cells

From spreadsheetgear document, if you want to open Excel from a file you need to create workbookSet then invoke OpenFromStream method. I have tested, it works in my side.
StorageFile file = await openPicker.PickSingleFileAsync();
if (file != null)
{
using (var steam = await file.OpenAsync(FileAccessMode.ReadWrite))
{
var workbookSet = Factory.GetWorkbookSet(CultureInfo.CurrentUICulture);
var workbook = workbookSet.Workbooks.OpenFromStream(steam.AsStream());
var worksheet = workbook.Worksheets[0];
var Used = worksheet.UsedRange;
var items = Used.Value;
}
}
else
{
return;
}

I have a question, I use the code to open the excel, and if I want to save it, what is it the code?.
I use the code of open the excel. If you dont want open a windows dialog, and you prefer to give de path directly, you can use the following code:
var folder = await StorageFolder.GetFolderFromPathAsync(#"C:\Excel_Modelo");
var file = await folder.GetFileAsync("Modelo.xlsx");
if (file != null)
{
var workbookSet = Factory.GetWorkbookSet(CultureInfo.CurrentUICulture);
IWorkbook workbook = workbookSet.Workbooks.OpenFromStream(steam.AsStream());
var worksheet = workbook.Worksheets[0];
var Used = worksheet.UsedRange;
var items = Used.Value;
}

Related

Error using OpenXML to read a .docx file from a memorystream to a WordprocessingDocument to a string and back

I have an existing library that I can use to receive a docx file and return it. The software is .Net Core hosted in a Linux Docker container.
It's very limited in scope though and I need to perform some actions it can't do. As these are straightforward I thought I would use OpenXML, and for my proof of concept all I need to do is to read a docx as a memorystream, replace some text, turn it back into a memorystream and return it.
However the docx that gets returned is unreadable. I've commented out the text replacement below to eliminate that, and if I comment out the call to the method below then the docx can be read so I'm sure the issue is in this method.
Presumably I'm doing something fundamentally wrong here but after a few hours googling and playing around with the code I am not sure how to correct this; any ideas what I have wrong?
Thanks for the help
private MemoryStream SearchAndReplace(MemoryStream mem)
{
mem.Position = 0;
using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(mem, true))
{
string docText = null;
StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream());
docText = sr.ReadToEnd();
//Regex regexText = new Regex("Hello world!");
//docText = regexText.Replace(docText, "Hi Everyone!");
MemoryStream newMem = new MemoryStream();
newMem.Position = 0;
StreamWriter sw = new StreamWriter(newMem);
sw.Write(docText);
return newMem;
}
}
If your real requirement is to search and replace text in a WordprocessingDocument, you should have a look at this answer.
The following unit test shows how you can make your approach work if the use case really demands that you read a string from a part, "massage" the string, and write the changed string back to the part. It also shows one of the shortcomings of any other approach than the one described in the answer already mentioned above, e.g., by demonstrating that the string "Hello world!" will not be found in this way if it is split across w:r elements.
[Fact]
public void CanSearchAndReplaceStringInOpenXmlPartAlthoughThisIsNotTheWayToSearchAndReplaceText()
{
// Arrange.
using var docxStream = new MemoryStream();
using (var wordDocument = WordprocessingDocument.Create(docxStream, WordprocessingDocumentType.Document))
{
MainDocumentPart part = wordDocument.AddMainDocumentPart();
var p1 = new Paragraph(
new Run(
new Text("Hello world!")));
var p2 = new Paragraph(
new Run(
new Text("Hello ") { Space = SpaceProcessingModeValues.Preserve }),
new Run(
new Text("world!")));
part.Document = new Document(new Body(p1, p2));
Assert.Equal("Hello world!", p1.InnerText);
Assert.Equal("Hello world!", p2.InnerText);
}
// Act.
SearchAndReplace(docxStream);
// Assert.
using (WordprocessingDocument wordDocument = WordprocessingDocument.Open(docxStream, false))
{
MainDocumentPart part = wordDocument.MainDocumentPart;
Paragraph p1 = part.Document.Descendants<Paragraph>().First();
Paragraph p2 = part.Document.Descendants<Paragraph>().Last();
Assert.Equal("Hi Everyone!", p1.InnerText);
Assert.Equal("Hello world!", p2.InnerText);
}
}
private static void SearchAndReplace(MemoryStream docxStream)
{
using (WordprocessingDocument wordDocument = WordprocessingDocument.Open(docxStream, true))
{
// If you wanted to read the part's contents as text, this is how you
// would do it.
string partText = ReadPartText(wordDocument.MainDocumentPart);
// Note that this is not the way in which you should search and replace
// text in Open XML documents. The text might be split across multiple
// w:r elements, so you would not find the text in that case.
var regex = new Regex("Hello world!");
partText = regex.Replace(partText, "Hi Everyone!");
// If you wanted to write changed text back to the part, this is how
// you would do it.
WritePartText(wordDocument.MainDocumentPart, partText);
}
docxStream.Seek(0, SeekOrigin.Begin);
}
private static string ReadPartText(OpenXmlPart part)
{
using Stream partStream = part.GetStream(FileMode.OpenOrCreate, FileAccess.Read);
using var sr = new StreamReader(partStream);
return sr.ReadToEnd();
}
private static void WritePartText(OpenXmlPart part, string text)
{
using Stream partStream = part.GetStream(FileMode.Create, FileAccess.Write);
using var sw = new StreamWriter(partStream);
sw.Write(text);
}

where are app scripts stored on Google Drive?

I found a useful script long ago and installed it. Now I want to delete it so it's no longer running, but I have no idea where it is stored so I can delete it. And I don't know it's exact filename to search for it. How do I find the script?? it watches a shared folder on Google Drive and emails me when the contents of the folder are changed.
I need to find this script and delete it.... suggestions????
How about something like this? It uses Mime types to find the scripts.
function findGoogleScripts() {
var ssNew = SpreadsheetApp.create("GoogleScriptsOnMyDrive");
SpreadsheetApp.setActiveSpreadsheet(ssNew);
var sheet = ssNew.getSheets()[0];
var files = DriveApp.getFiles();
sheet.appendRow(["File Name", "Mime Type"]);
while (files.hasNext()) {
var mType, theFile;
var tempArray = [];
theFile = files.next();
mType = theFile.getMimeType();
if (mType.equals("application/vnd.google-apps.script")) {
tempArray.push(theFile.getName());
tempArray.push(mType);
sheet.appendRow(tempArray);
}
}
}

execute a vbscript from an adobe air app

Is it possible to run a vbscript file from an air app?
I haven't found any examples of this and am unsure if it's possible.
I have a vbscript that automates some printing from word, and wanted to make a front end for this is adobe air.
Many thanks
I believe you can try to achieve your goal using Native Process
Follow some example running a .exe file
var nativeProcessStartupInfo:NativeProcessStartupInfo = new NativeProcessStartupInfo();
var file:File = File.applicationDirectory.resolvePath("test.exe");
nativeProcessStartupInfo.executable = file;
var processArgs:Vector.<String> = new Vector.<String>();
processArgs.push("hello");
nativeProcessStartupInfo.arguments = processArgs;
process = new NativeProcess();
process.addEventListener(ProgressEvent.STANDARD_OUTPUT_DATA, onOutputData);
process.start(nativeProcessStartupInfo);
public function onOutputData(event:ProgressEvent):void
{
var stdOut:ByteArray = process.standardOutput;
var data:String = stdOut.readUTFBytes(process.standardOutput.bytesAvailable);
trace("Got: ", data);
}

Related on Custom Timer Job in sharepoint 2010

How to create a custom job to export an Excel file in a list which has only 2 columns(Title,Description) in a sharepoint 2010?i want the coding part of this question?
Reading Data from Excel and writing into a sharepoint list,this has to be done through custom job coding
Thanks in Advance...
Naresh
Use OpenXMLSDK - a free download that needs to be installed on the server.
[...]
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
public class OffBookAssetLibraryEventReceiver : SPItemEventReceiver
{
public override void ItemUpdated(SPItemEventProperties properties)
{
// This if statement is to work around the sharepoint issue of this event firing twice.
if (properties.AfterProperties["vti_sourcecontrolcheckedoutby"] == null && properties.BeforeProperties["vti_sourcecontrolcheckedoutby"] != null)
{
byte[] workSheetByteArray = properties.ListItem.File.OpenBinary();
Stream stream = new MemoryStream(workSheetByteArray);
Package spreadsheetPackage = Package.Open(stream, FileMode.Open, FileAccess.ReadWrite);
SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(spreadsheetPackage);
SharedStringTablePart shareStringTablePart = spreadsheetDocument.WorkbookPart.SharedStringTablePart;
Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.Sheets;
try
{
foreach (Sheet sheet in sheets)
{
var worksheetPart = (WorksheetPart)spreadsheetDocument.WorkbookPart.GetPartById(sheet.Id.Value);
IEnumerable<Row> rows = worksheetPart.Worksheet.GetFirstChild<SheetData>().Elements<Row>();
if (rows.Count() > 0)
{
int rowNumber = 0;
foreach (Row row in rows)
{
IEnumerable<Cell> cells = row.Elements<Cell>();
Cell title = null;
Cell description = null;
title = cells.ToArray()[0];
description = cells.ToArray()[1];
// This is the code used to extract cells from excel that are NOT inline (Inline cells are decimal and dates - although dates are stored as int)
int index = int.Parse(title.CellValue.Text);
string titleString = spreadsheetDocument.WorkbookPart.SharedStringTablePart.SharedStringTable.Elements<SharedStringItem>().ElementAt(index).InnerText;
index = int.Parse(description.CellValue.Text);
string descriptionString = spreadsheetDocument.WorkbookPart.SharedStringTablePart.SharedStringTable.Elements<SharedStringItem>().ElementAt(index).InnerText;
//Insert into your sharepoint list here!
}
}
}
}
}
}
}
I recommend putting this code into an event receiver on the document library (as seen above).
Have you looked at Excel REader for .NET
http://exceldatareader.codeplex.com/
Open the Excel File
Take a look at the Excel Services for SharePoint 2010. There is a walkthrough explaining the required steps to open an excel file.
SharePoint Custom Timer Job
To create a custom SharePoint timer job, you have to create a class that inherits from SPJobDefinition. A complete tutorial can be found in this blog post: Creating Custom Timer Job in SharePoint 2010.

opening url based file in filestream

I have a document which is stored in doc library of sharepoint..now i want to open and read data from it ...how can i do it ..filestream does not take url as input ..please help.
Try SPFile.OpenBinaryStream
From SharePoint 2007 - Read content from SPFile:
string content = string.Empty;
using (SPSite oSite = new SPSite("http://localhost/"))
{
using (SPWeb oWeb = oSite.OpenWeb())
{
SPDocumentLibrary doclib = (SPDocumentLibrary)oWeb.GetList(DocLibUrl);
SPFile htmlFile = doclib.Items[0].File;
using (System.IO.StreamReader reader = new System.IO.StreamReader(htmlFile.OpenBinaryStream()))
{
content = reader.ReadToEnd();
}
}
}
Sounds like you need to use a HTTPRequest object to retrieve the file. Here is a code example:
http://geeknotes.wordpress.com/2008/01/10/saving-a-possibly-binary-file-from-a-url-in-c/