DataSource Controls :: Transform LINQ Dataset Into A Matrix For Export

Jun 1, 2010

I've got a data table with columns in which include Item, Category and Value (and others, but those are the only relevant ones for this problem) that I access via LINQ in a C# ASP.Net MVC app. I want to transform these into a matrix and output that as a CSV file to pull into Excel as matrix with the items down the side, the categories across the top and the values in the row cells. However, I don't know how many, or what, categories there will be in this table, nor will there always be a record for each item/category combination.

I've written this by looping round, getting my "master category" list, then looking again for each item, filling in either blank or Value, depending on whether the item/category record exists, but as there are currently 27000 records in the table, this isn't as fast as I'd like. Is there a slicker and faster way I can do this, maybe via LINQ (firing into a quicker SQL statement so the DB server can do the leg-work), or will any method essentially come back to what I am doing?

View 2 Replies


Similar Messages:

DataSource Controls :: LINQ To DataSet And LINQ To Object

Mar 9, 2010

txtLastName.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(0).Last_Name.ToString();

Like that I have large number of controls on my form. I have dought, if I assigned like this, db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(0).Last_Name.ToString(); to every control, then I have set of controls like,

ddlSalutation.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(0).Salutation.ToString();
txtLastName.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(0).Last_Name.ToString();
txtFirstName.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(0).First_Name.ToString();
txtMI.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(0).Middle_Initial.ToString();
txtAddress.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(0).Home_Address.ToString();
txtCity.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(0).City.ToString();
ddlState.SelectedItem.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(0).State.ToString();
txtZip.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(0).Zip_Code.ToString();
txtSSNo.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(0).Ssn.ToString();
txtMRNo.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(0).Mr_No.ToString();
txtDOB.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(0).Birth_Date.ToString();
RBGender.SelectedItem.Value = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(0).Gender.ToString();
RBMaritalStatus.SelectedItem.Value = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(0).Marital_Status.ToString();
txtHomePhone.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(0).Home_Phone.ToString();
txtWorkPhone.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(0).WorkPhone.ToString();
txtCellPhone.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(0).CellPhone.ToString();
ddlSuffix.SelectedItem.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(0).Suffix.ToString();
txtReligion.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(0).Religion.ToString();
txtEmail.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(0).Email.ToString();
txtSSOName.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(0).Ssn.ToString();
txtPatientKin.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(0).Patient_Kin.ToString();
txtRelationWithPatient.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(0).Kin_Relation.ToString();
txtPhoneNo.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(0).Kin_Phone.ToString();
ddlPreferredPharmacy.SelectedItem.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(0).Id_Pharmacy.ToString();
txtEmergencyContactName.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(0).Emergency_Contact_Name.ToString();
txtEmergencyContactNumber.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(0).Emergency_Contact_Phone.ToString();
txtRelation.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(0).Kin_Relation.ToString();
txtRace.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(0).Race.ToString();
ddlHowDidPatientFindUs.SelectedItem.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(0).How_Found.ToString();
txtEmployerName.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(0).Employer_Name.ToString();
txtEmployerOccupation.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(0).Employer_Occupation.ToString();
txtEmployerPhone.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(0).Employer_Cell_Phone.ToString();
txtEmployerAddress.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(0).Employer_Address.ToString();
txtEmployerCity.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(0).Employer_City.ToString();
ddlEmployerState.SelectedItem.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(0).Employer_State.ToString();
txtEmployerZip.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(0).Employer_Zip.ToString();
txtRecordsReleasedTo.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(0).Records_Released_To.ToString();
txtOtherInfo.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(0).Other_Info.ToString();
txtPopupNote.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(0).Popup_e.ToString();
ddlPPlanName.SelectedItem.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(0).Insurance_Name.ToString();
txtPGroupNo.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(0).Ins_Group_No.ToString();
txtPIDNo.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(0).Ins_Id_No.ToString();
txtPPhone.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(0).Ins_Plan_Phone.ToString();
txtPVerifiedWith.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(0).Ins_Verified_With.ToString();
txtPVerifiedPhone.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(0).Ins_Verified_Phone.ToString();
txtPEffectiveDate.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(0).Ins_Effective_Date.ToString();
txtPExtDate.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(0).Ins_Ext_Date.ToString();
if (db.usp_ATI_FetchPatientDetails(iPatientID).Count() > 0)
{
txtPGLastName.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(0).Ins_Grn_Name.ToString();
txtPGFirstName.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(0).Ins_Grn_Name.ToString();
txtPGMI.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(0).Ins_Grn_MI.ToString();
txtPGBirthGDate.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(0).Ins_Grn_Dob.ToString();
txtPGAddress.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(0).Ins_Grn_Address.ToString();
txtPGCity.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(0).Ins_Grn_City.ToString();
ddlPGState.SelectedItem.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(0).Ins_Grn_State.ToString();
txtPGZip.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(0).Ins_Grn_Zip.ToString();
txtPGEmployerFirstName.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(0).Grn_Emp_Fname.ToString();
txtPGEmployerLastName.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(0).Grn_Emp_Lname.ToString();
txtPGEmployerPhone.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(0).Grn_Emp_Phone.ToString();
txtPGEmployerOccupation.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(0).Grn_Emp_Occupation.ToString();
txtPGEmployerAddress.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(0).Grn_Emp_Address.ToString();
txtPGEmployerCity.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(0).Grn_Emp_City.ToString();
ddlPGState.SelectedItem.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(0).Grn_Emp_State.ToString();
txtPGEmployerZip.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(0).Grn_Emp_Zip.ToString();
ddlPGPatientRelationshipToGuarantor.SelectedItem.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(0).Ins_Grn_Rel_With_Pat.ToString();
txtPGOtherInsuranceNotes.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(0).Ins_Other_Notes.ToString();
txtPGAuthorization.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(0).Ins_Authorization.ToString();
txtPGAob.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(0).Ins_AOB.ToString();
}
if (db.usp_ATI_FetchPatientDetails(iPatientID).Count() > 1)
{
txtSGLastName.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(1).Ins_Grn_Name.ToString();
txtSGFirstName.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(1).Ins_Grn_Name.ToString();
txtSGMI.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(1).Ins_Grn_MI.ToString();
txtSGBirthGDate.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(1).Ins_Grn_Dob.ToString();
txtSGAddress.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(1).Ins_Grn_Address.ToString();
txtSGCity.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(1).Ins_Grn_City.ToString();
ddlSGState.SelectedItem.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(1).Ins_Grn_State.ToString();
txtSGZip.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(1).Ins_Grn_Zip.ToString();
txtSGEmployerFirstName.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(1).Grn_Emp_Fname.ToString();
txtSGEmployerLastName.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(1).Grn_Emp_Lname.ToString();
txtSGEmployerPhone.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(1).Grn_Emp_Phone.ToString();
txtSGEmployerOccupation.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(1).Grn_Emp_Occupation.ToString();
txtSGEmployerAddress.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(1).Grn_Emp_Address.ToString();
txtSGEmployerCity.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(1).Grn_Emp_City.ToString();
ddlSGState.SelectedItem.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(1).Grn_Emp_State.ToString();
txtSGEmployerZip.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(1).Grn_Emp_Zip.ToString();
ddlSGPatientRelationshipToGuarantor.SelectedItem.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(1).Ins_Grn_Rel_With_Pat.ToString();
txtSGOtherInsuranceNotes.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(1).Ins_Other_Notes.ToString();
txtSGAuthorization.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(1).Ins_Authorization.ToString();
txtSGAob.Text = db.usp_ATI_FetchPatientDetails(iPatientID).ElementAt(1).Ins_AOB.ToString();
}

My question is that, for each control the Stored Procedure called or not? If it is yes then it is time consuming and I need to use LINQ to DataSet or LINQ to Object rather than to call SP for each control. What is difference between LINQ to DataSet and LINQ to Object?

View 5 Replies

DataSource Controls :: How To Export The Current DataSet Bound To A Gridview To Excel

Mar 12, 2011

I have a GridView populated by an ObjectDataSource. I also have several DropDownLists filtering the ObjectDataSource. I found a link providing a way to export a DataSet (or DataTable) to Excel here:

http://msmvps.com/blogs/deborahk/archive/2009/07/23/writing-data-from-a-datatable-to-excel.aspx

ow I can ensure that filters applied to the ObjectDataSource when the method is called are applied. In short, how can I ensure what the UI is displaying is what the file will include when exported?

View 2 Replies

DataSource Controls :: Linq To SQL Vs ADO.NET Dataset ?

Jun 12, 2010

What are the advantages and disadvantages of linq to sql and ado.net dataset?

Which method should I use to connect, retrive, update and generally operate on data from a ME SQL database?

View 1 Replies

DataSource Controls :: View The LINQ To DataSet Query?

Feb 23, 2010

I'm trying to find an easy way to view the query that has been generated as part of the LINQ to DataSet syntax in my application. I found Scott Gu's blog and his creation of the Linq to SQL Debug Visualizer but it doesn't appear to work for my application. I am using OracleClient if that is important.

My next step is to simply configure the Oracle Manager for the database to see the query but I can't believe there's not an easy way to view this generated query.

View 3 Replies

ADO.NET :: Transform This Sql Code Into Linq?

Nov 4, 2010

i am new with linq and i wanna do something like this in linq:

[Code]....

how can i do this?

View 2 Replies

DataSource Controls :: What's Faster Working With DataSet OR Working With Collections (LINQ To Entities)

May 21, 2010

I mean, what is the faster way to get as fast as I can more than one table with stored procedure? Is there any study what is faster and why? There is a big problem getting more than one table at once with Entities, so the only way is DataSet. But I was told DataSet work very slow. Is that true?

View 2 Replies

C# LINQ Unable To Enumerate Matrix

Aug 31, 2010

I declared a 3 X 3 Matrix

int[,] matrix=new int[3,3]
{
{1,2,3},
{4,5,6},
{11,34,56}
};

when i try to enumerate it like var diagonal = matrix.AsQueryable().Select(); I am unbale to convert it as enumerable collection.How to do that?

View 2 Replies

DataSource Controls :: How To Connect Typed DataSet Using DataSet.XSD File

Feb 4, 2010

Today I am facing the problem with Typed DataSet using DataSet.XSd file, And How to fetch, Delete and Update the Database through Dataset.xsd file.

View 9 Replies

DataSource Controls :: Microsoft Matrix Framework DataGrid - Update Command - Convert Empty Strings To NULL?

Sep 30, 2010

we have a AutoGenerateColumns-enabled WmxDataGrid in which we are able to update table rows in a DataBase connected with a SqlDataSource.

Each time we clear a field an empty string is written to the database where we want to write DBNull values.

At the moment we generate the update string via UPDATE... SET.. and the SQL Server function NULLIF(value, '').

Works proper but when I want to add the values to e.NewValues in BeginUpdate event I'm not able to read the values from the auto generated text boxes. How do I do that? Is there an easier way to automatically convert empty strings to NULL values?

View 2 Replies

DataSource Controls :: How To Copy Required Row In Dataset To A New Dataset

Mar 5, 2010

how do i copy required row in dataset to a new dataset. i have bind a xml into a dataset and i need to display say row 3 to 5 only so i do a for loop but i have encounter problem when trying to copy the rows to a new dataset.

do i have to write the xml to datatable and bind it to dataset and from there copy over ?

View 7 Replies

Data Controls :: Export DataSet Or DataTable To PDF In (WinForms) Application

Mar 31, 2014

 I want to get print out for Dataset which creates a pdf file as out put.

View 1 Replies

Forms Data Controls :: Export Multiple Grids And Dataset To Excel Sheet

Feb 9, 2010

In a page im having multiple data grids with some data tables.How can i export all these to excel sheet without any change in the alignment.

View 6 Replies

Forms Data Controls :: How To Export Dataset To Excel When Click Gridview Linkbutton

Jun 28, 2010

I want to Export dataset data to excel ,when i click gridview linkbutton.

My Scenior is : Actually i am Passing a parameter from griview linkbutton.Depending on the parameter value .I want to export dataset data to excel.

View 7 Replies

DataSource Controls :: Linq To SQL Set Linq Object Propertychanged?

Mar 12, 2010

I am writing a plugin to help with a current ERP system we have that I am not allowed to modify the data structure at all. The table I am dealing with has over 100 columns and I am wanting to set my linq object propertychanged event and submitchanges or do I really have list out each property and set it equal to the new one?Below is an example of what I am trying to do:

[Code]....

View 4 Replies

Forms Data Controls :: Selecting Radio Buttons In A Gridview With Dataset From Linq Query?

Oct 13, 2010

I've got a gridview that will allow clients to edit options they've already entered on another page. The gridview has three radio buttons in it each with a value of 1,2,3. The option value in the dataset is 1,2 or 3 respectively. I would like to have the radiobutton with the corresponding value selected in the gridview so they can see what they previously chose and will then be able to edit, if they wish.

Here's my code so far:

[Code]....

View 6 Replies

C# - EXPORT Dataset To EXCEL

Feb 12, 2011

I am using the following code to export fields from a database table into excel. What I want to do is be able to write a SQL statement to retrieve fields from multiple tables and export them into excel. This code only allows me to export one table. Also, how can I display a save prompt dialog?

protected void export_Click(object sender, EventArgs e)
{
string sql = null;
string data = null;
string path = save_as.Text;
int i = 0;
int j = 0;
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
//connectionString = "data source=servername;initial catalog=databasename;user id=username;password=password;";
SqlConnection cnn = new SqlConnection(GetConnectionString());
cnn.Open();
sql = "SELECT Story, CreationDate FROM Story";
SqlDataAdapter dscmd = new SqlDataAdapter(sql, cnn);
DataSet ds = new DataSet();
dscmd.Fill(ds);
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
for (j = 0; j <= ds.Tables[0].Columns.Count - 1; j++)
{
data = ds.Tables[0].Rows[i].ItemArray[j].ToString();
xlWorkSheet.Cells[i + 1, j + 1] = data;
}
}
xlWorkBook.SaveAs(path+".xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
//MessageBox.Show("Excel file created , you can find the file c:\csharp.net-informations.xls");
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
//MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
}
finally
{
GC.Collect();
}
}

View 2 Replies

Export Excel File From Dataset In C#?

May 29, 2010

i have data in sql server i want to export to data with asp.net C#

View 3 Replies

Web Forms :: Export A Big Dataset To Excel Via Web?

Feb 24, 2010

Actually I have a SQL query that a user exports to excel in our web server. I did it in c# with Visual Studio 2003 (.Net v1.1): I get the data from a SQL server into a Dataset, then with this method I create the XLS file:

private void ExportAsExcelFile ( DataSet dtExport )
{
Response.Clear() ;
Response.ContentType = "application/vnd.ms-excel";
Response.ContentEncoding = System.Text.Encoding.UTF8 ;
Response.Charset = string.Empty ;
Response.AddHeader ( "Content-Disposition", "attachment;filename=data.xls" ) ;
System.IO.StringWriter objStringWriter = new StringWriter () ;
System.Web.UI.HtmlTextWriter objHtmlTextWriter = new System.Web.UI.HtmlTextWriter(objStringWriter) ;
DataGrid objDatagrid = new DataGrid () ;
objDatagrid.DataSource = dtExport ;
objDatagrid.DataBind () ;
objDatagrid.RenderControl ( objHtmlTextWriter ) ;
Response.Write (objStringWriter.ToString()) ;
Response.End () ;
}

Well, this works when the SQL query has 10.000 rows and so on. But now the query has more than 200.000 rows, and I´m getting a TimeOut Error trying to export the data. I read about generate this big files with a Store Procedure and the SQL Commad: BCP [URL], but I tryed and it fails. I have no permissions to execute this command. Is there any other way to export this SQL data to Excel via a ASPX page?

View 1 Replies

VS 2005 - Export Dataset To Excel

Sep 9, 2011

I have a dataset wity multiple table, the same dataset need to export to excel

dataset.table[0] data
dataset.table[1] data in the same excel sheet

View 1 Replies

VS 2008 - Export Dataset To Excel Attachment

Jul 12, 2012

I need to give users of my asp.net/vb.net web application the ability to click a button which will then send them an e-mail with the contents of a SQL query attached as an Excel e-mail attachment.

I can manage all of this apart from getting the contents of a VB dataset object into an Excel file on my server.

I know how to export a gridview to Excel at the client end, but my boss has been adamant that he wants the button to send an e-mail with the results attached - I have no need to display a gridview at all.

How to export the contents of a datareader or dataset directly into an Excel file at the server side?

View 12 Replies

DataSource Controls :: Compile In Order To Get The System.Linq.Dynamic Namespace / Dynamic Linq Error

Apr 20, 2010

I've added the Dynamic.cs file to my project and have set it's Build Action = Compile in order to get the System.Linq.Dynamic namespace.

However, when I try to use any of the new code I am getting an ambiguous call error; see below.

[Code]....

View 2 Replies

Web Forms :: Export The Dataset Values Into Excel In Application

Mar 9, 2011

I am trying to Export the dataset values into Excel in my application, its working for first time. Again if i click the export button [second time] the button does't cause postback and the entire page is not postback.

View 4 Replies

C# - Numbers Are Converted As Text When Export Dataset To Excel

Jul 8, 2010

Iam exporting dataset to excel , the numbers on the sheet shown as text when export it to excel. Here is the code:

public class Excel
{
const int rowLimit = 65000;
private static string getWorkbookTemplate()
{
StringBuilder sb = new StringBuilder(818);
sb.AppendFormat(@"<?xml version=""1.0""?>{0}", Environment.NewLine);
sb.AppendFormat(@"<?mso-application progid=""Excel.Sheet""?>{0}", Environment.NewLine);
sb.AppendFormat(@"<Workbook xmlns=""urn:schemas-microsoft-com:office:spreadsheet""{0}", Environment.NewLine);
sb.AppendFormat(@" xmlns:o=""urn:schemas-microsoft-com:office:office""{0}", Environment.NewLine);
sb.AppendFormat(@" xmlns:x=""urn:schemas-microsoft-com:office:excel""{0}", Environment.NewLine);
sb.AppendFormat(@" xmlns:ss=""urn:schemas-microsoft-com:office:spreadsheet""{0}", Environment.NewLine);
sb.AppendFormat(@" xmlns:html=""[URL]
sb.AppendFormat(@" <Styles>{0}", Environment.NewLine);
sb.AppendFormat(@" <Style ss:ID=""Default"" ss:Name=""Normal"">{0}", Environment.NewLine);
sb.AppendFormat(@" <Alignment ss:Vertical=""Bottom""/>{0}", Environment.NewLine);
sb.AppendFormat(@" <Borders/>{0}", Environment.NewLine);
sb.AppendFormat(@" <Font ss:FontName=""Verdana"" x:Family=""Swiss"" ss:Size=""12"" ss:Color=""#0000A0""/>{0}", Environment.NewLine);
sb.AppendFormat(@" <Interior/>{0}", Environment.NewLine);
sb.AppendFormat(@" <NumberFormat/>{0}", Environment.NewLine);
sb.AppendFormat(@" <Protection/>{0}", Environment.NewLine);
sb.AppendFormat(@" </Style>{0}", Environment.NewLine);
sb.AppendFormat(@" <Style ss:ID=""s62"">{0}", Environment.NewLine);
sb.AppendFormat(@" <Font ss:FontName=""Calibri"" x:Family=""Swiss"" ss:Size=""11"" ss:Color=""#000000""{0}", Environment.NewLine);
sb.AppendFormat(@" ss:Bold=""1""/>{0}", Environment.NewLine);
sb.AppendFormat(@" </Style>{0}", Environment.NewLine);
sb.AppendFormat(@" <Style ss:ID=""s63"">{0}", Environment.NewLine);
sb.AppendFormat(@" <NumberFormat ss:Format=""Short Date""/>{0}", Environment.NewLine);
sb.AppendFormat(@" </Style>{0}", Environment.NewLine);
sb.AppendFormat(@" </Styles>{0}", Environment.NewLine);
sb.Append(@"{0}
</Workbook>");
return sb.ToString();
}
private static string replaceXmlChar(string input)
{
input = input.Replace("&", "&");
input = input.Replace("<", "<");
input = input.Replace(">", ">");
input = input.Replace(""", """);
input = input.Replace("'", "&apos;");
return input;
}
private static string getCell(Type type, object cellData)
{
Object data = (cellData is DBNull) ? "" : cellData;
if (type.Name.Contains("Int") || type.Name.Contains("Double") || type.Name.Contains("Decimal")) return string.Format("<Cell><Data ss:Type="Number">{0}</Data></Cell>", data);
if (type.Name.Contains("Date") && data.ToString() != string.Empty)
{
return string.Format("<Cell ss:StyleID="s63"><Data ss:Type="DateTime">{0}</Data></Cell>", Convert.ToDateTime(data).ToString("yyyy-MM-dd"));
}
return string.Format("<Cell><Data ss:Type="String">{0}</Data></Cell>", replaceXmlChar(data.ToString()));
}
private static string getWorksheets(DataSet source)
{
StringWriter sw = new StringWriter();
if (source == null || source.Tables.Count == 0)
{
sw.Write("<Worksheet ss:Name="Sheet1">
<Table>
<Row><Cell><Data ss:Type="String"></Data></Cell></Row>
</Table>
</Worksheet>");
return sw.ToString();
}
foreach (DataTable dt in source.Tables)
{
if (dt.Rows.Count == 0)
sw.Write("<Worksheet ss:Name="" + replaceXmlChar(dt.TableName) + "">
<Table>
<Row><Cell ss:StyleID="s62"><Data ss:Type="String"></Data></Cell></Row>
</Table>
</Worksheet>");
else
{
//write each row data
int sheetCount = 0;
for (int i = 0; i < dt.Rows.Count; i++)
{
if ((i % rowLimit) == 0)
{
//add close tags for previous sheet of the same data table
if ((i / rowLimit) > sheetCount)
{
sw.Write("
</Table>
</Worksheet>");
sheetCount = (i / rowLimit);
}
sw.Write("
<Worksheet ss:Name="" + replaceXmlChar(dt.TableName) +
(((i / rowLimit) == 0) ? "" : Convert.ToString(i / rowLimit)) + "">
<Table>");
//write column name row
sw.Write("
<Row>");
foreach (DataColumn dc in dt.Columns)
sw.Write(string.Format("<Cell ss:StyleID="s62"><Data ss:Type="String">{0}</Data></Cell>", replaceXmlChar(dc.ColumnName)));
sw.Write("</Row>");
}
sw.Write("
<Row>");
foreach (DataColumn dc in dt.Columns)
sw.Write(getCell(dc.DataType, dt.Rows[i][dc.ColumnName]));
sw.Write("</Row>");
}
sw.Write("
</Table>
</Worksheet>");
}
}
return sw.ToString();
}
public static string GetExcelXml(DataTable dtInput, string filename)
{
string excelTemplate = getWorkbookTemplate();
DataSet ds = new DataSet();
ds.Tables.Add(dtInput.Copy());
string worksheets = getWorksheets(ds);
string excelXml = string.Format(excelTemplate, worksheets);
return excelXml;
}
public static string GetExcelXml(DataSet dsInput, string filename)
{
string excelTemplate = getWorkbookTemplate();
string worksheets = getWorksheets(dsInput);
string excelXml = string.Format(excelTemplate, worksheets);
return excelXml;
}
public static void ToExcel(DataSet dsInput, string filename, HttpResponse response)
{
string excelXml = GetExcelXml(dsInput, filename);
response.Clear();
response.AppendHeader("Content-Type", "application/vnd.ms-excel");
response.AppendHeader("Content-disposition", "attachment; filename=" + filename);
response.Write(excelXml);
response.Flush();
response.End();
}
public static void ToExcel(DataTable dtInput, string filename, HttpResponse response)
{
DataSet ds = new DataSet();
ds.Tables.Add(dtInput.Copy());
ToExcel(ds, filename, response);
}
}

View 1 Replies

Export DataSet To Multiple Excel Sheets And Download Into A Zip File Using C#?

Jan 21, 2011

how to Export DataSet to Multiple Excel Sheets and download those file into a zip in C# asp.net?

View 2 Replies







Copyrights 2005-15 www.BigResource.com, All rights reserved