Can't able to use Formula in Excel while using Aspose.cells to import - excel-2010

I have been using Aspose.cells to import Excel sheet with data.
The Excel sheet consists of a Salary column for which I am assigning Decimal value. Even though I am assigning the decimal value from the database the columns are assigned as string format.
Once I double click on each cell then it is converting to number format.
Due to this, I can't able to use the formula like "=SUM(M1:M20)".
I am using the following function to download excel using Aspose.cells
protected void DownloadExcel(string psPlanNo, string psSuffix)
{
try
{
DataTable dtExcelData = GetDataTableValue();
dtExcelData.TableName = psPlanNo + "Template";
var workbook = new Workbook();
var worksheet = workbook.Worksheets[0];
worksheet.Cells.ImportDataTable(dtExcelData, true, "A1");
worksheet.AutoFilter.Range = worksheet.Cells.FirstCell.Name + ":" + worksheet.Cells.LastCell.Name;
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=" + psPlanNo + psSuffix + ".xlsx");
worksheet.AutoFitColumns();
Aspose.Cells.Style style = worksheet.Cells["A1"].GetStyle();
style.ForegroundThemeColor = new ThemeColor(ThemeColorType.Accent1, 0);
style.Font.Color = Color.White;
style.Pattern = BackgroundType.Solid;
for (int lnColumn = 0; lnColumn <= worksheet.Cells.MaxColumn; lnColumn++)
worksheet.Cells[0, lnColumn].SetStyle(style);
Cells cells = worksheet.Cells;
Aspose.Cells.Style fontStyle = new Aspose.Cells.Style();
Aspose.Cells.Style stylefont = workbook.Styles[workbook.Styles.Add()];
stylefont.Font.Name = "Calibri";
stylefont.Font.Size = 12;
StyleFlag flag = new StyleFlag();
flag.FontName = true;
flag.FontSize = true;
cells.ApplyStyle(stylefont, flag);
using (MemoryStream memoryStream = new MemoryStream())
{
workbook.Save(memoryStream, SaveFormat.Xlsx);
memoryStream.WriteTo(Response.OutputStream);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.SuppressContent = true;
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
}
catch (SqlException sql)
{
DbException(sql, MethodBase.GetCurrentMethod().Name);
}
catch (Exception ex)
{
GenericException(ex, MethodBase.GetCurrentMethod().Name);
}
}
Does anyone have a solution for this issue?
Thanks in Advance

I got solution, change this line of code
worksheet.Cells.ImportDataTable(dtExcelData, true, "A1");
to:
worksheet.Cells.ImportDataTable(dtExcelData, true, 0, 0, true, true);
(Note: the last Boolean parameter "convertStringToNumber" should be set to true)
Now it's working fine.. :)

Related

How to use "content disposition attachment" in OpenXml

I have an ASP.NET MVC 4 site that creates an Excel file using OPEN XML SDK. My controller method generates the OPEN XML Excel document and is downloading it.
But the user should see the Excel file in the browser.
I know
Response.AddHeader("content-disposition", "attachment; filename=" + fileName + "");
is responsible for it. But I don't know how to implement this in openXnl method. I am not using http response here. Or how can I use it? Please help me on this
This is my Excel generating method, and I tried to implement AddHeader "content-disposition" but nothing works:
public static void GenerateExcelOpenXML(string FolderPath, DataSet tableSet)
{
WorkbookPart wBookPart = null;
var datetime = DateTime.Now.ToString().Replace("/", "_").Replace(":", "_");
string FilePath = FolderPath + "Report_" + datetime + ".xlsx";
using (SpreadsheetDocument spreadsheetDoc = SpreadsheetDocument.Create(FilePath, SpreadsheetDocumentType.Workbook))
{
wBookPart = spreadsheetDoc.AddWorkbookPart();
wBookPart.Workbook = new Workbook();
uint sheetId = 1;
spreadsheetDoc.WorkbookPart.Workbook.Sheets = new Sheets();
Sheets sheets = spreadsheetDoc.WorkbookPart.Workbook.GetFirstChild<Sheets>();
WorkbookStylesPart wbsp = wBookPart.AddNewPart<WorkbookStylesPart>();
wbsp.Stylesheet = CreateStylesheet();
wbsp.Stylesheet.Save();
foreach (DataTable table in tableSet.Tables)
{
WorksheetPart wSheetPart = wBookPart.AddNewPart<WorksheetPart>();
Sheet sheet = new Sheet() { Id = spreadsheetDoc.WorkbookPart.GetIdOfPart(wSheetPart),
SheetId = sheetId, Name = table.TableName };
sheets.Append(sheet);
SheetData sheetData = new SheetData();
wSheetPart.Worksheet = new Worksheet();
Row headerRow = new Row();
Columns columns = new Columns();
int ColumnNumber = 1;
foreach (DataColumn column in table.Columns)
{
Cell cell = new Cell();
cell.DataType = CellValues.String;
cell.CellValue = new CellValue(column.ColumnName);
cell.StyleIndex = 2;
headerRow.AppendChild(cell);
Column column1 = new Column();
column1.Width = 30;
column1.Min = Convert.ToUInt32(ColumnNumber);
column1.Max = Convert.ToUInt32(ColumnNumber);
column1.CustomWidth = true;
columns.AppendChild(column1);
ColumnNumber = ColumnNumber + 1;
}
wSheetPart.Worksheet.AppendChild(columns);
sheetData.AppendChild(headerRow);
foreach (DataRow dr in table.Rows)
{
Row row = new Row();
foreach (DataColumn column in table.Columns)
{
Cell cell = new Cell();
cell.DataType = CellValues.String;
cell.CellValue = new CellValue(dr[column].ToString());
cell.StyleIndex = 1;
row.AppendChild(cell);
}
sheetData.AppendChild(row);
}
sheetId++;
wSheetPart.Worksheet.AppendChild(sheetData);
// sheetData.AddHeader("content-disposition", "attachment; filename=" + fileName + "");
// how can I implement here?
}
}
}

mvc 4 asp.net - export data to .csv from a local .xls file

I would be grateful if you could please help me with the code below: I am fairly new to C# and Razor. I am trying to get data from an excel sheet and displaying it on the screen using a jQuery Jtable. I can get it to be displayed but its not exporting the data to CSV file. I am using MVC 4 Razor ASP.NET
here's my controller action code:
private void ExportToCsv(object sender, System.EventArgs e)
{
string Path = #"C:\\5Newwithdate.xls";
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source= '" + Path + "';Extended Properties=" + (char)34 + "Excel 8.0;IMEX=1;" + (char)34 + "");
OleDbDataAdapter da = new OleDbDataAdapter("select * from [Sheet1$]", con);
con.Close();
System.Data.DataTable data = new System.Data.DataTable();
da.Fill(data);
SQLDBBillingProvider sql = new SQLDBBillingProvider();
// var billingList = sql.GetAllBilling(jtStartIndex, jtPageSize, jtSorting);
// data.Rows.OfType<DataRow>().Select(dr => dr.Field<MyType>(columnName)).ToList();
List<TopPlayed> daa = new List<TopPlayed>();
foreach (DataRow p in data.Rows)
{
//daa.Add(p.Field<string>("Track Statistics"));
//daa.Add(p.Field<string>("Track Name"));
TopPlayed top = new TopPlayed()
{
TrackID = p.Field<double>("ID").ToString(),
TrackName = p.Field<string>("Track Name"),
ArtistName = p.Field<string>("Artist Name"),
Times = p.Field<double>("NoOfPlays").ToString()
};
daa.Add(top);
}
var toptracks = new List<TopPlayed>();
// toptracks.Add(GetHeader());
int k = -5;
for (int i = 0; i < 5; i++)
{
//static data
var trackInfo = new TopPlayed();
trackInfo.TrackID = "abc" + i;
trackInfo.TrackName = "xyz" + i;
trackInfo.ArtistName = "" + i;
trackInfo.Times = "" + i;
toptracks.Add(trackInfo);
}
System.Web.UI.WebControls.GridView gridvw = new System.Web.UI.WebControls.GridView();
gridvw.DataSource = toptracks.ToList().Take(7); //bind the datatable to the gridview
gridvw.DataBind();
Response.ClearContent();
Response.ContentType = "application/vnd.ms-excel;name='Excel'";
Response.AddHeader("content-disposition", "attachment;filename=TopTracks.csv");
StringWriter swr = new StringWriter();
HtmlTextWriter tw = new HtmlTextWriter(swr);
gridvw.RenderControl(tw);
Response.Write(swr.ToString());
Response.End();
}
Thanks in advance.
From an existing, working, project:
HttpContext.Response.AddHeader("content-disposition", "attachment; filename=" + filename);
var sw = new StreamWriter(new MemoryStream());
// Write the strings here..
sw.WriteLine(...) etc
// Flush the stream and reset the file cursor to the start
sw.Flush();
sw.BaseStream.Seek(0, SeekOrigin.Begin);
// return the stream with Mime type
return new FileStreamResult(sw.BaseStream, "text/csv");
Just tweak the variables to suit your filename and data writing method.
e.g.
HttpContext.Response.AddHeader("content-disposition", "attachment; filename=" + filename);
var sw = new StreamWriter(new MemoryStream());
// Write the data here..
HtmlTextWriter tw = new HtmlTextWriter(sw);
gridvw.RenderControl(tw);
// Flush the stream and reset the file cursor to the start
sw.Flush();
sw.BaseStream.Seek(0, SeekOrigin.Begin);
// return the stream with Mime type
return new FileStreamResult(sw.BaseStream, "text/csv");
In the context of your original question it will look something like:
public ActionResult ExportToCsv()
{
string Path = #"C:\\5Newwithdate.xls";
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source= '" + Path + "';Extended Properties=" + (char)34 + "Excel 8.0;IMEX=1;" + (char)34 + "");
OleDbDataAdapter da = new OleDbDataAdapter("select * from [Sheet1$]", con);
con.Close();
System.Data.DataTable data = new System.Data.DataTable();
da.Fill(data);
SQLDBBillingProvider sql = new SQLDBBillingProvider();
// var billingList = sql.GetAllBilling(jtStartIndex, jtPageSize, jtSorting);
// data.Rows.OfType<DataRow>().Select(dr => dr.Field<MyType>(columnName)).ToList();
List<TopPlayed> daa = new List<TopPlayed>();
foreach (DataRow p in data.Rows)
{
//daa.Add(p.Field<string>("Track Statistics"));
//daa.Add(p.Field<string>("Track Name"));
TopPlayed top = new TopPlayed()
{
TrackID = p.Field<double>("ID").ToString(),
TrackName = p.Field<string>("Track Name"),
ArtistName = p.Field<string>("Artist Name"),
Times = p.Field<double>("NoOfPlays").ToString()
};
daa.Add(top);
}
var toptracks = new List<TopPlayed>();
// toptracks.Add(GetHeader());
int k = -5;
for (int i = 0; i < 5; i++)
{
//static data
var trackInfo = new TopPlayed();
trackInfo.TrackID = "abc" + i;
trackInfo.TrackName = "xyz" + i;
trackInfo.ArtistName = "" + i;
trackInfo.Times = "" + i;
toptracks.Add(trackInfo);
}
System.Web.UI.WebControls.GridView gridvw = new System.Web.UI.WebControls.GridView();
gridvw.DataSource = toptracks.ToList().Take(7); //bind the datatable to the gridview
gridvw.DataBind();
HttpContext.Response.ClearContent();
HttpContext.Response.AddHeader("content-disposition", "attachment; filename=filename=TopTracks.csv");
HttpContext.Response.AddHeader("Expires", "0");
var sw = new StreamWriter(new MemoryStream());
// Write the data here..
HtmlTextWriter tw = new HtmlTextWriter(sw);
gridvw.RenderControl(tw);
// Flush the stream and reset the file cursor to the start
sw.Flush();
sw.BaseStream.Seek(0, SeekOrigin.Begin);
// return the stream with Mime type
return new FileStreamResult(sw.BaseStream, "text/csv");
}

How do I get an in-memory chart (or image) into an in-memory OpenXML document?

I'm having a nightmare of a time trying to add a Chart to a MemoryStream in-memory.
I'm creating a Word document on the fly using OpenXML and I have a chart that is also being dynamically generated from data in the database.
I get the template from the database as a byte array, passing that into a method that also takes a business object that holds a bunch of data to populate bookmarks held within that template.
Here's the method:
public Stream Parse(byte[] array, AudiometryReport AudReport)
{
using (MemoryStream Stream = new MemoryStream())
{
Stream.Write(array, 0, (int)array.Length);
Stream.Position = 0;
using (document = WordprocessingDocument.Open(Stream, true))
{
XDocument doc = document.MainDocumentPart.GetXDocument();
List<XElement> bookmarks = doc.Descendants()
.Where(n => n.NodeType == XmlNodeType.Element && n.Name.LocalName == "bookmarkStart")
.ToList();
PropertyInfo[] reportInfo = AudReport.GetType().GetProperties();
foreach (XElement bm in bookmarks)
{
try
{
if (bm.LastAttribute.Value == "AudiometryChart")
{
string partId = InsertImage(document.MainDocumentPart);
var element = AddImageToDocument(document.MainDocumentPart, partId);
//var element = InsertImageXElement(partId);
//bm.ReplaceWith(new XElement(w + "r", element));
}
else
{
string val = reportInfo.Single(x => x.Name == bm.LastAttribute.Value).GetValue(AudReport, null).ToString();
bm.ReplaceWith(new XElement(w + "r",
new XElement(w + "t", val)));
}
}
catch
{ }
}
document.MainDocumentPart.PutXDocument();
//foreach (BookmarkStart bm in (IEnumerable<BookmarkStart>)document.MainDocumentPart.Document.Descendants<BookmarkStart>())
//{
// if (bm.Name == "AudiometryChart")
// {
// // Insert the chart object here.
// //AddImage(document);
// }
// populateStaffDetails(AudReport.Report.Employee, bm);
// populateAudiometryDetails(AudReport, bm);
//}
}
MemoryStream s = new MemoryStream();
Stream.WriteTo(s);
s.Position = 0;
return s;
}
}
The InsertImage image takes the MainDocumentPart and attaches a new ImagePart from the image I stream from the database. I pass the ID of that part back to the calling method.
private string InsertImage(MainDocumentPart docPart)
{
//DrawingsPart dp = docPart.AddNewPart<DrawingsPart>();
//ImagePart part = dp.AddImagePart(ImagePartType.Png, docPart.GetIdOfPart(dp));
ImagePart part = docPart.AddImagePart(ImagePartType.Png);
Chart cht = new ChartBuilder().DoChart(Data, new string[] { "Left", "Right", "Normal" });
using (MemoryStream ms = new MemoryStream())
{
cht.SaveImage(ms, ChartImageFormat.Png);
ms.Position = 0;
part.FeedData(ms);
}
//int count = dp.ImageParts.Count<ImagePart>();
int count = docPart.ImageParts.Count<ImagePart>();
return docPart.GetIdOfPart(part);
}
The last part is some serious nastiness that is allegdly required to add one image to one word document, but what the hell - here it is anyway:
private Run AddImageToDocument(MainDocumentPart docPart, string ImageRelId)
{
string ImageFileName = "Audiometry Chart Example";
string GraphicDataUri = "http://schemas.openxmlformats.org/drawingml/2006/picture";
long imageLength = 990000L;
long imageHeight = 792000L;
var run = new Run(
new Drawing(
new wp.Inline(
new wp.Extent() { Cx = imageLength, Cy = imageHeight },
new wp.EffectExtent()
{
LeftEdge = 19050L,
TopEdge = 0L,
RightEdge = 9525L,
BottomEdge = 0L
},
new wp.DocProperties()
{
Id = (UInt32Value)1U,
Name = "Inline Text Wrapping Picture",
Description = ImageFileName
},
new wp.NonVisualGraphicFrameDrawingProperties(
new a.GraphicFrameLocks() { NoChangeAspect = true }),
new a.Graphic(
new a.GraphicData(
new pic.Picture(
new pic.NonVisualPictureProperties(
new pic.NonVisualDrawingProperties() { Id = (UInt32Value)0U, Name = ImageFileName },
new pic.NonVisualPictureDrawingProperties()),
new pic.BlipFill(
new a.Blip() { Embed = ImageRelId },
new a.Stretch(
new a.FillRectangle())),
new pic.ShapeProperties(
new a.Transform2D(
new a.Offset() { X = 0L, Y = 0L },
new a.Extents() { Cx = imageLength, Cy = imageHeight }),
new a.PresetGeometry(
new a.AdjustValueList()) { Preset = a.ShapeTypeValues.Rectangle }))
) { Uri = GraphicDataUri }))
{
DistanceFromTop = (UInt32Value)0U,
DistanceFromBottom = (UInt32Value)0U,
DistanceFromLeft = (UInt32Value)0U,
DistanceFromRight = (UInt32Value)0U
}
));
return run;
}
So I've solved issues where the memory stream was causing problems by closing prematurely and probably a dozen other unnecessary amateur garden path problems but that image will just not show up in my document. Frustrating. Suggestions or divine inspiration very welcome right now.
(this question has been heavily edited so some answers may not relate to the wording of this question).
I've just tested your AddImageToDocument function in a small test
scenario using the following code:
string partId = ...
Run element = AddImageToDocument(newdoc.MainDocumentPart, partId);
Paragraph p = new Paragraph() { RsidParagraphAddition = "00EA6221", RsidRunAdditionDefault = "008D25CC" };
p.AppendChild(element);
newdoc.MainDocumentPart.Document.Body.Append(p);
// Save the word document here...
Everything works as expected and the image shows up in the word document.
Then I've come to the conclusion that the problem in your code must be the replacement of the bookmarkStart tag and the conversion
of the Run (containing the image) to an XElement.
So, I've modified your code in the following way (using XElement.Parse to convert
an OpenXmlElement to a XElement):
foreach (XElement bm in bookmarks)
{
try
{
if (bm.LastAttribute.Value == "AudiometryChart")
{
string partId = InsertImage(document.MainDocumentPart);
Run element = AddImageToDocument(document.MainDocumentPart, partId);
bm.ReplaceWith(XElement.Parse(element.OuterXml)); // Use XElement.Parse to convert an OpenXmlElement to an XElement.
}
else
{
... }
}
}
catch
{
}
}
The image now shows up in the word document.
Then I've analyzed the word document using the
OpenXml SDK productivity tool and found that the bookmarkEnd tags still exist in the document.
To remove those tags use the following code:
List<XElement> bookmarksEnd = doc.Descendants()
.Where(n => n.NodeType == XmlNodeType.Element && n.Name.LocalName == "bookmarkEnd")
.ToList();
foreach (XElement x in bookmarksEnd)
{
x.Remove();
}
Edit 3: :o)
Ok, I found the problem.
If you initialize the document's MemoryStream with the doc content, the buffer will be fixed in size and not editable. Just changed the init to write the doc content after creation and all seemd to work fine.
//using (MemoryStream stream = new MemoryStream (docxFile))
using (MemoryStream stream = new MemoryStream ())
{
stream.Write (docxFile, 0, docxFile.Length);
stream.Position = 0;
using (WordprocessingDocument docx = WordprocessingDocument.Open (stream, true))
{
[....]
Cheers

Read Image stored in Oracle using Long DataType

I want to read the image stored in Oracle Long datatype.
Number of images are stored in a remote Oracle database in a column with datatype long. I just need to retrieve those images and show them on my aspx page.
I could retrieve the image from database but when tried to caste it to byte array, it threw error that, string can not be converted to byte[]'.
Anybody have any suggestions on how to retrieve these images stored in long column in database.
byte[] signatureBlobReceived = cls_TBL_BROKER_BL.GetInstance().GetSignatureBlobFromAccountNumber_BL(strCRNnumber);
return File(signatureBlobReceived, "image/jpeg");
public byte[] GetSignatureBlobFromAccountNumber_BL()
{
object SignatureBlob = null;
Database db = DatabaseFactory.CreateDatabase("imageConnectionString");
DbCommand dbc = db.GetSqlStringCommand(ConfigurationSettings.AppSettings["signqry"].ToString());
dbc.CommandType = CommandType.Text;
SignatureBlob = db.ExecuteScalar(dbc);
byte[] array = Encoding.ASCII.GetBytes(Convert.ToString(SignatureBlob));
string aa = string.Empty;
return array;
}
Query used is:
<add key="signqry" value="SELECT image FROM table1"/> `
Try this (odp.net)
string connStr = "User Id=user;Password=pwd;Data Source=mySID;";
OracleConnection _conn = new OracleConnection(connStr);
_conn.Open();
string sel = #"select long_raw_col from long_raw_test";
OracleCommand cmd = new OracleCommand(sel, _conn);
cmd.InitialLONGFetchSize = 5000;
OracleDataReader reader = cmd.ExecuteReader();
int rows = 0;
// loop through rows from table
while (reader.Read())
{
rows++;
byte[] buf = new byte[5000];
long bytesRead = reader.GetBytes(reader.GetOrdinal("long_raw_col"), 0, buf, 0, 5000);
FileStream fs = new FileStream("C:\\test\\test_long" + rows + ".dat", FileMode.Create);
fs.Write(buf, 0, (int)bytesRead);
fs.Close();
Console.WriteLine("Row " + rows + ": Read " + bytesRead + " bytes from table, see test_long" + rows + ".dat");
}
This example just reads the long raw data from Oracle into a byte array, then outputs to a file. Note the InitalLONGFetchSize > 0.
I use this class :my database is informix and the images are stored in Byte type .Hope this can help you.
public class MyPhoto
{
public static Stream RetrievePhoto()
{
DBConnection DAL_Helper = new DBConnection(ConfigurationSettings.AppSettings["connection"].ToString());
Byte[] myByteBuff;
Stream myImgStream;
string qry = "----------";
DataTable dt = DAL_Helper.Return_DataTable(qry);
try
{
if (dt.Rows.Count > 0)
{
if (!string.IsNullOrEmpty(dt.Rows[0][0].ToString()))
{
myByteBuff = (Byte[])((object)(dt.Rows[0][0]));
myImgStream = new MemoryStream(myByteBuff);
}
else
{
myImgStream = RetrievePhotoNoProfile();
}
}
else
{
myImgStream = RetrievePhotoNoProfile();
}
}
catch (Exception ex)
{
myImgStream = RetrievePhotoNoProfile();
}
return myImgStream;
}
public static byte[] StreamToByteArray(Stream stream)
{
if (stream is MemoryStream)
{
return ((MemoryStream)stream).ToArray();
}
else
{
return ReadFully(stream);
}
}
public static byte[] ReadFully(Stream input)
{
byte[] buffer = new byte[input.Length];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}
private static Stream RetrievePhotoNoProfile()
{
string noprofileimgPath = HttpContext.Current.Server.MapPath("~/images/noprofile.png");
System.IO.FileStream fs = new System.IO.FileStream(noprofileimgPath, System.IO.FileMode.Open, FileAccess.Read);
byte[] ba = new byte[fs.Length];
fs.Read(ba, 0, (int)fs.Length);
Stream myImgStream = new MemoryStream(ba);
fs.Close();
return myImgStream;
}
public static Image byteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
return returnImage;
}
}

Silverlight 3 File Dialog Box

Ok - I have a WCF Service which reads an excel file from a certain location and strips the data into an object. What I need is the ability to allow users of my program to Upload an excel sheet to the file location that my Service uses.
Alternitivley I could pass the Uploaded excel sheet to the service directly.
Can anyone help with this. My service code is:
public List<ImportFile> ImportExcelData(string FileName)
{
//string dataSource = Location + FileName;
string dataSource = Location;
string conStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + dataSource.ToString() + ";Extended Properties=Excel 8.0;";
var con = new OleDbConnection(conStr);
con.Open();
var data = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
var sheetName = data.Rows[0]["TABLE_NAME"].ToString();
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [" + sheetName + "] WHERE Status = '4'", con);
OleDbDataAdapter oleda = new OleDbDataAdapter();
oleda.SelectCommand = cmd;
DataSet ds = new DataSet();
oleda.Fill(ds, "Employees");
DataTable dt = ds.Tables[0];
var _impFiles = new List<ImportFile>();
foreach (DataRow row in dt.Rows)
{
var _import = new ImportFile();
_import.PurchaseOrder = row[4].ToString();
try
{
var ord = row[8].ToString();
DateTime dati = Convert.ToDateTime(ord);
_import.ShipDate = dati;
}
catch (Exception)
{
_import.ShipDate = null;
}
ImportFile additionalData = new ImportFile();
additionalData = GetAdditionalData(_import.PurchaseOrder);
_import.NavOrderNo = additionalData.NavOrderNo;
_import.IsInstall = additionalData.IsInstall;
_import.SalesOrderId = additionalData.SalesOrderId;
_import.ActivityID = additionalData.ActivityID;
_import.Subject = additionalData.Subject ;
_import.IsMatched = (_import.ShipDate != null & _import.NavOrderNo != "" & _import.NavOrderNo != null & _import.ShipDate > DateTime.Parse("01/01/1999") ? true : false);
_import.UpdatedShipToField = false;
_import.UpdatedShipToFieldFailed = false;
_import.CreateNote = false;
_import.CreateNoteFailed = false;
_import.CompleteTask = false;
_import.CompleteTaskFailed = false;
_import.FullyCompleted = 0;
_import.NotCompleted = false;
_impFiles.Add(_import);
}
oleda.Dispose();
con.Close();
//File.Delete(dataSource);
return _impFiles;
}
You will want to modify your service to accept a Stream instead of a filename, then you can save if off to a file (or parse it directly from the Stream, although I don't know how to do that).
Then in your Silverlight app you could do something like this:
private void Button_Click(object sender, RoutedEventArgs ev)
{
var dialog = new OpenFileDialog();
dialog.Filter = "Excel Files (*.xls;*.xlsx;*.xlsm)|*.xls;*.xlsx;*.xlsm|All Files (*.*)|*.*";
if (dialog.ShowDialog() == true)
{
var fileStream = dialog.File.OpenRead();
var proxy = new WcfService();
proxy.ImportExcelDataCompleted += (s, e) =>
{
MessageBox.Show("Import Data is at e.Result");
// don't forget to close the stream
fileStream.Close();
};
proxy.ImportExcelDataAsync(fileStream);
}
}
You could also have your WCF service accept a byte[] and do something like this.
private void Button_Click(object sender, RoutedEventArgs ev)
{
var dialog = new OpenFileDialog();
dialog.Filter = "Excel Files (*.xls;*.xlsx;*.xlsm)|*.xls;*.xlsx;*.xlsm|All Files (*.*)|*.*";
if (dialog.ShowDialog() == true)
{
var length = dialog.File.Length;
var fileContents = new byte[length];
using (var fileStream = dialog.File.OpenRead())
{
if (length > Int32.MaxValue)
{
throw new Exception("Are you sure you want to load > 2GB into memory. There may be better options");
}
fileStream.Read(fileContents, 0, (int)length);
}
var proxy = new WcfService();
proxy.ImportExcelDataCompleted += (s, e) =>
{
MessageBox.Show("Import Data is at e.Result");
// no need to close any streams this way
};
proxy.ImportExcelDataAsync(fileContents);
}
}
Update
Your service could look like this:
public List<ImportFile> ImportExcelData(Stream uploadedFile)
{
var tempFile = HttpContext.Current.Server.MapPath("~/uploadedFiles/" + Path.GetRandomFileName());
try
{
using (var tempStream = File.OpenWrite(tempFile))
{
uploadedFile.CopyTo(tempStream);
}
//string dataSource = Location + FileName;
string dataSource = tempFile;
string conStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + dataSource.ToString() +
";Extended Properties=Excel 8.0;";
var con = new OleDbConnection(conStr);
con.Open();
}
finally
{
if (File.Exists(tempFile))
File.Delete(tempFile);
}
}
Thanks Bendewey that was great. Had to amend it slightly -
My Service:
var tempFile = #"c:\temp\" + Path.GetRandomFileName();
try
{
int length = 256;
int bytesRead = 0;
Byte[] buffer = new Byte[length];
// write the required bytes
using (FileStream fs = new FileStream(tempFile, FileMode.Create))
{
do
{
bytesRead = uploadedFile.Read(buffer, 0, length);
fs.Write(buffer, 0, bytesRead);
}
while (bytesRead == length);
}
uploadedFile.Dispose();
string conStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + dataSource.ToString() + ";Extended Properties=Excel 8.0;";
var con = new OleDbConnection(conStr);
Thanks Again for your help

Resources