I am using VS2010, Silverlight 5.0
I am trying to Import Data from Excel file to Grid, for that I am using an 'OpenFileDialog'. User can Input Excel file using OpenFileDialog like this
OpenFileDialog dlg = new OpenFileDialog();
dlg.Multiselect = false;
dlg.Filter = "Excel Sheet(*.xls)|*.xls|All Files(*.*)|*.*";
bool bResult = (bool)dlg.ShowDialog();
if (!bResult)
return "";
FileInfo info = dlg.File;
StatusText.Text = info.Name;
Stream s = info.OpenRead();
StreamReader reader = new StreamReader(s);
string xml = reader.ReadToEnd();
var doc = XDocument.Parse(xml);
In Case of Microsoft Excel Format 2003 or 2007(.xls file) above code works fine and gives me values from Excel in a string.
But in case of Microsoft Excel Format 2010(.xlsx file) the reader.ReadToEnd() does not return values in proper format so the next line, give me following Error.
var doc = XDocument.Parse(xml);
'Data at the root level is invalid. Line 1, position 1'
How can I solve this error, or what is the best way to import data from excel?
Related
I have the following table :
CREATE TABLE DI_Simulation
(
[city] nvarchar(255),
[profession] nvarchar(255)
);
I load the data from an URL with a Script task where I created a class Simulation and added two string attributes. I then deserialize the downloaded JSON data and create output rows.
I specify that the output columns city and profession are of type DT_WSTR but the following characters [é,à,è,...] are always replaced...
I tried different collations on both columns but no changes were seen. I also tried forcing UTF8 conversion on the Script Task but that also didn't work.
Any suggestions ?
EDIT: I should also mention that I have other tables where the insertion is made correctly, but this one especially has this issue, which I'm thinking the Script Task has something to do with it.
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3;
// Convert json string to .net object using the old school JavaScriptSerializer class
string Uri = "https://....";
JavaScriptSerializer serialize = new JavaScriptSerializer
{
MaxJsonLength = Int32.MaxValue,
};
var simulation = serialize.Deserialize<Simulation[]>(DownloadJson(Uri));
EDIT 2:
WebClient client = new WebClient();
Stream stream = client.OpenRead(Url);
StreamReader streamreader = new StreamReader(stream, System.Text.Encoding.GetEncoding(1252));
var ags = streamreader.ReadToEnd();
/*System.IO.File.WriteAllText(#"C:\Users\hhamdani\Desktop\Data Integration Objetcs\simulation_data.json",
ags,
System.Text.Encoding.GetEncoding(1252));*/
var simulation = serialize.Deserialize<Simulation[]>(ags);
Instead of downloading with DownloadJson, I used streamreader to get the Json Data from the URL and forced the Encoding, when I save the data on a txt file it's good, but on the Database it's the same issue.
Works fine from a script source component based on my reproduction
Setup
Table creation
A trivial table with two columns
CREATE TABLE dbo.[SO_71842511] (
[TestCase] int,
[SomeText] nvarchar(50)
)
SCR Do Unicode
Proof that we can inject unicode characters into the data flow task from a script source.
Define the Script Task as a Source. Add 2 columns to the output, one int, one DT_WSTR
using System;
using System.Data;
using Microsoft.SqlServer.Dts.Pipeline.Wrapper;
using Microsoft.SqlServer.Dts.Runtime.Wrapper;
[Microsoft.SqlServer.Dts.Pipeline.SSISScriptComponentEntryPointAttribute]
public class ScriptMain : UserComponent
{
public override void CreateNewOutputRows()
{
Output0Buffer.AddRow();
Output0Buffer.SomeText = "e e plain";
Output0Buffer.TestCase = 0;
Output0Buffer.AddRow();
Output0Buffer.SomeText = "é e forward";
Output0Buffer.TestCase = 1;
Output0Buffer.AddRow();
Output0Buffer.SomeText = "à a back";
Output0Buffer.TestCase = 2;
Output0Buffer.AddRow();
Output0Buffer.SomeText = "è e backward";
Output0Buffer.TestCase = 3;
}
}
Results
WebClient client = new WebClient();
Stream stream = client.OpenRead(Url);
StreamReader streamreader = new StreamReader(stream, System.Text.Encoding.UTF8);
var ags = streamreader.ReadToEnd();
This did the job for me.
Thanks #billinkc
Got this code below, how can I send an excel file to the printer?
Edit: I want to send an existing file (excel) to my "Microsoft Print to PDF" printer and then have it save it as a new file (pdf).
PrintDocument doc = new PrintDocument()
{
PrinterSettings = new PrinterSettings()
{
PrinterName = "Microsoft Print to PDF",
PrintToFile = true,
PrintFileName = System.IO.Path.Combine(#AppDomain.CurrentDomain.BaseDirectory + "\\pdf\\", "filename.pdf"),
}
};
doc.Print();
This is selenium code using apache Poi where I am reading a file value from excel and opening a link while writing a string value in excel file its giving me null point exception. can you tell me what is wrong ?
on last line I am getting errors, the lines are:-
sheet1.getRow(i).getCell(2).setCellValue(linkLocatin);
File src = new File ("C:\\Sandeep\\Selenium\\automationproject1\\Testdata.xlsx");
My all code:-
FileInputStream fis = new FileInputStream(src);
XSSFWorkbook wb =new XSSFWorkbook (fis);
XSSFSheet sheet1 =wb.getSheetAt(0);
int rowcount= sheet1.getLastRowNum();
XSSFCell cel;
//System.out.println ("Test data is " + data0);
System.out.println ("rowncount is = "+ rowcount);
for (int i=1; i<= rowcount;i++)
{
//Set browser profile and then get link from excel
FirefoxProfile prof = new FirefoxProfile();
prof.setPreference("media.windows-media-foundation.enabled", false);
prof.setPreference("media.directshow.enabled", false);
prof.setAcceptUntrustedCertificates(true);
prof.setPreference("browser.download.dir","C:\\Sandeep\\Selenium\\automationproject1\\Download1");
prof.setPreference("browser.helperApps.alwaysAsk.force", false);
prof.setPreference("browser.helperApps.neverAsk.saveToDisk", "audio/x-mpeg-3");
prof.setPreference("browser.download.folderList", 2);
prof.setPreference("browser.download.manager.showWhenStarting",false);
WebDriver driver = new FirefoxDriver(prof);
String data0 = sheet1.getRow(i).getCell(1).getStringCellValue();
System.out.println(data0);
// open the link in browser
driver.get(data0);
WebElement link = driver.findElement(By.linkText("Download the recording"));
String linkLocatin = link.getAttribute("href");
sheet1.getRow(i).getCell(2).setCellValue(linkLocatin);
While setting up string value in excel it's showing null point exception ..W
OK I managed to upload the word DOCX into my SQL Server database into a varbinary (Max) column.
I can retrieve the DOCX from the database and covert it from varbinary back into an array and offer it as a download with:
Byte[] bytes = (Byte[])dt.Rows[0]["TD_DocFile"];
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = dt.Rows[0]["TD_DocContentType"].ToString();
Response.AddHeader("content-disposition", "attachment;filename="
+ dt.Rows[0]["TD_DocTitle"].ToString());
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
Instead of downloading the document I would prefer to use it in variable so I exchange placeholders in it.
I tried to find a way to convert it to a string or so I can use it for docx eg.
DocX letter = this.document();
Best option I saw so far was the filestream version
public static MemoryStream databaseFileRead(string varID) {
MemoryStream memoryStream = new MemoryStream();
using (var varConnection = Locale.sqlConnectOneTime(Locale.sqlDataConnectionDetails))
using (var sqlQuery = new SqlCommand(#"SELECT [RaportPlik] FROM [dbo].[Raporty] WHERE [RaportID] = #varID", varConnection)) {
sqlQuery.Parameters.AddWithValue("#varID", varID);
using (var sqlQueryResult = sqlQuery.ExecuteReader())
if (sqlQueryResult != null) {
sqlQueryResult.Read();
var blob = new Byte[(sqlQueryResult.GetBytes(0, 0, null, 0, int.MaxValue))];
sqlQueryResult.GetBytes(0, 0, blob, 0, blob.Length);
//using (var fs = new MemoryStream(memoryStream, FileMode.Create, FileAccess.Write)) {
memoryStream.Write(blob, 0, blob.Length);
//}
}
}
return memoryStream;
}
But I couldn't convert the binary array bytes nor the memory stream into a variable docx would understand. Maybe I just looked for the wrong conversation. Can someone give me a hint please?
The field is called TD_DocContentType from the database. I can accept that I am weak on the conversion in this instance. I can't see what I am doing wrong. Need a new idea please.
Kind Regards,
Rene
I found the solution for my problem. Took a while and lot of more research to do. I tried to tackle the problem from the wrong angle.
This solution reads the binary field from the database and writes it as a file to an internal web folder called doctemp.
private void download(DataTable dt)
{
var physicalPath = Server.MapPath("~\\doctemp\\{0}");
string outputFileName = string.Format(physicalPath, dt.Rows[0]["TD_DocTitle"]);
filename = outputFileName;
Byte[] bytes = (Byte[])dt.Rows[0]["TD_DocFile"];
File.WriteAllBytes(outputFileName, bytes);
}
Writing my first silverlight application.
I need to deliver some bitmap that the customer will choose ( used OpenFileDialog ) to the server side ( using web service ).
After the customer choosing the bitmap - i cant access the file and break hit to byte array because i dont see the file full path on the OpenFileDialog object properties.
How can i do it ?
( i have method that get Bitmap and return the bitmap as byte array )
I did that before, here is part of it:
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "Images (*.png; *.jpg)| *.png; *.jpg";
dialog.Multiselect = false;
if (dialog.ShowDialog() == true)
{
using (System.IO.Stream stream = dialog.File.OpenRead())
{
BinaryReader binaryReader = new BinaryReader(stream);
// here are the bytes you want, put them somewhere to send them to the server
byte[] imageBytes = binaryReader.ReadBytes((int)stream.Length);
// here is the filename if you need it
string filename = System.IO.Path.GetFileNameWithoutExtension(dialog.File.Name);
stream.Close();
}
}