Saving data to excel file - asp.net

I basically need to save the output of the stored procedure to a .xls or .xlsx Excel file. I am able to do it to a csv but not to Excel. Can someone help? Please see the code below
var result = DealingContext.PopulateUnitRebateData(true, Convert.ToDateTime("2015-01-16")).ToList();
if (result.Count > 0)
{
string header = #"""Firm ID"",""AccountNumber"",""Portfolio Name"",""Currency"",""Amount"",""Value Date""";
StringBuilder sb = new StringBuilder();
sb.AppendLine(header);
foreach (var i in result)
{
sb.AppendLine(string.Join(",",
string.Format(#"""{0}""", i.FirmID),
string.Format(#"""{0}""", i.AccountNumber),
string.Format(#"""{0}""", i.PortfolioName),
string.Format(#"""{0}""", i.Currency),
string.Format(#"""{0}""", i.Amount),
string.Format(#"""{0}""", i.ValueDate)));
}
HttpContext context = HttpContext.Current;
context.Response.Write(sb.ToString());
context.Response.ContentType = "application/vnd.ms-excel";
context.Response.AddHeader("Content-Disposition", "attachment; filename=TestData.xls");
context.Response.End();
}

The reason you cant save it to excel is because excel is formatted differently than csv.
The best (and easiest) library I have used for saving data to excel is LinqToExcel https://code.google.com/p/linqtoexcel/
Nuget
PM> Install-Package LinqToExcel

you can try to export Data to Excel using Microsoft.Office.Interop.Excel
Pass the DataSet,which has atleast one DataTable and valid fileName with Path.
public void WriteToExcel(DataSet dataSet , string fileNameWithPath)
{
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
try
{
string data = string.Empty;
//Setting up Columns on Excel
for (int i = 0; i < 1; i++)
{
for (int j = 0; j <= dataSet.Tables[0].Columns.Count - 1; j++)
{
data = dataSet.Tables[0].Columns[j].ColumnName.ToString();
xlWorkSheet.Cells[i + 1, j + 1] = data;
}
}
//data Insertion
for (int i = 0; i <= dataSet.Tables[0].Rows.Count - 1; i++)
{
for (int j = 0; j <= dataSet.Tables[0].Columns.Count - 1; j++)
{
xlWorkSheet.Cells[i + 2, j + 1].NumberFormat = "#"; //format as text
data = result.Tables[0].Rows[i].ItemArray[j].ToString();
xlWorkSheet.Cells[i + 2, j + 1] = data;
}
}
Excel.Range range = xlWorkSheet.Range[xlWorkSheet.Cells[1, 1], xlWorkSheet.Cells[1, result.Tables[0].Columns.Count]];
range.Font.Bold = true;
range.Interior.ColorIndex = 15;
range.EntireColumn.AutoFit();
xlWorkSheet.PageSetup.LeftMargin = 0.5;
xlWorkSheet.PageSetup.RightMargin = 0.5;
xlWorkSheet.PageSetup.Zoom = false;
xlWorkSheet.PageSetup.FitToPagesWide = 1;
xlWorkSheet.PageSetup.FitToPagesTall = Math.Ceiling((result.Tables[0].Rows.Count + 1) / 50.0);
xlWorkSheet.PageSetup.Orientation = Excel.XlPageOrientation.xlLandscape;
xlWorkSheet.PageSetup.PaperSize = Excel.XlPaperSize.xlPaperLetter;
xlWorkBook.SaveAsfileNameWithPathExcel.XlFileFormat.xlOpenXMLWorkbook, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
}
catch (Exception ex)
{
}
finally
{
xlWorkSheet = null;
xlWorkBook = null;
if (xlApp != null)
{
xlApp.Quit();
}
xlApp = null;
GC.Collect();
GC.WaitForPendingFinalizers();
}
}

Related

Index out of bound at xmlworkerhelper in c#

PaymentService.PaymentServiceClient client = new
PaymentService.PaymentServiceClient();
PaymentTransactionDto model = new PaymentTransactionDto();
OrderInvoiceDto invoiceData;
List<ProductRepoDto> products;
List<OrderTaxDto> taxes;
// Check payment status
int chkProduct = 0;
int chkCourse = 0;
int chkProductCourse = 0;
#region Get order details for invoice
var order_details = client.GetOrderDetailsForInvoice(Convert.ToInt32(Oid.Rows[0]["OrderId"]));
invoiceData = new OrderInvoiceDto();
if (order_details != null)
{
invoiceData = AutoMapConverter<PaymentService.OrderInvoiceDto, OrderInvoiceDto>.GetMappedData(order_details);
}
#endregion
#region Get Products list in order
var productList = client.GetOrderItemsByOrderId(Convert.ToInt32(Oid.Rows[0]["OrderId"]));
products = new List<ProductRepoDto>();
if (productList != null && productList.Count() > 0)
{
products = AutoMapConverter<PaymentService.ProductRepoDto, ProductRepoDto>.GetMappedList(productList.ToList());
}
#endregion
#region ADD Taxes
#region check product type
decimal Amount = 0;
foreach (var item in products)
{
if (item.TypeId == 1)
chkCourse = 1;
if (item.TypeId == 2)
chkProduct = 1;
if (chkCourse == 1 && chkProduct == 1)
chkProductCourse = 1;
Amount = Amount + (item.Amount * item.Quantity);
Amount = Amount - item.Discount;
}
#endregion
// Apply taxes
client.AddOrderTaxMappingDetails(Convert.ToInt64(orderid), Amount);
#endregion
#region Get Applied Tax details
var taxesApplied = client.GetOrderAppliedTaxes(Convert.ToInt64(orderid));
taxes = new List<OrderTaxDto>();
if (taxesApplied != null && taxesApplied.Count() > 0)
{
taxes = AutoMapConverter<PaymentService.OrderTaxDto, OrderTaxDto>.GetMappedList(taxesApplied.ToList());
}
#endregion
string pdfbody = System.IO.File.ReadAllText(Server.MapPath("~/Views/Payment/InvoiceView.cshtml"));
Document document = new Document();
string fileName = string.Format("{0}.pdf", invoiceData.OrderNumber);
var fpath = HttpContext.Current.Server.MapPath("~/Document/Payment/Invoice/");
if (!Directory.Exists(fpath))
{
Directory.CreateDirectory(fpath);
}
pdfbody = pdfbody.Replace("$name$", string.Format("{0} {1}", invoiceData.Billing_FirstName, invoiceData.Billing_LastName));
pdfbody = pdfbody.Replace("$address$", invoiceData.Billing_Address);
pdfbody = pdfbody.Replace("$billingCity$", invoiceData.Billing_City);
pdfbody = pdfbody.Replace("$billingPinCode$", invoiceData.Billing_PinCode.ToString());
pdfbody = pdfbody.Replace("$billingState$", invoiceData.Billing_State);
pdfbody = pdfbody.Replace("$billingCountry$", invoiceData.Billing_Country);
//pdfbody = pdfbody.Replace("$netAmt$", invoiceData.NetAmt.ToString());
//pdfbody = pdfbody.Replace("$grossAmt$", invoiceData.GrossAmt.ToString());
//pdfbody = pdfbody.Replace("$discountAmt$", invoiceData.DiscountAmt.ToString());
pdfbody = pdfbody.Replace("$orderNumber$", invoiceData.OrderNumber.Remove(0, 2));
pdfbody = pdfbody.Replace("$orderDate$", CommonFunctions.EpochToIstDate(Convert.ToDouble(invoiceData.OrderDate)));
StringBuilder b = new StringBuilder();
decimal totalAmount = 0;
foreach (var item in products)
{
if (!string.IsNullOrEmpty(item.ActivationKey))
item.ActivationKey = string.Format("Activation Key:{0}", item.ActivationKey);
b.AppendFormat("<tr><td width='60%'>{0}<br/>{1}</td>", item.ProductName, item.ActivationKey);
b.AppendFormat("<td width='10%' align='left'>{0}</td>", item.Quantity);
b.AppendFormat("<td width='30%' align='right'>{0}</td></tr>", (item.Amount * item.Quantity) - item.Discount);
totalAmount = totalAmount + (item.Amount * item.Quantity);
totalAmount = totalAmount - item.Discount;
}
pdfbody = pdfbody.Replace("$OrderDetailsList$", Convert.ToString(b));
if (taxes != null && taxes.Count > 0)
{
b = new StringBuilder();
foreach (var item in taxes)
{
b.AppendFormat("<tr><td width='80%' colspan='2'>{0} ({1}%)</td>", item.TaxName, item.Percentage);
b.AppendFormat("<td width='20%' align='right'>{0}</td></tr>", item.Amount);
}
pdfbody = pdfbody.Replace("$OrderTaxDetailsList$", Convert.ToString(b));
}
else
{
pdfbody = pdfbody.Replace("$OrderTaxDetailsList$", "");
}
pdfbody = pdfbody.Replace("$netAmt$", totalAmount.ToString());
pdfbody = pdfbody.Replace("$rupees$", CommonFunctions.ConvertNumbertoWords(Convert.ToInt32((int)Math.Ceiling(totalAmount))));
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(fpath + fileName, FileMode.Create));
document.Open();
StringReader sr = new StringReader(pdfbody);
XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, sr);
document.Close();
I want to generate pdf invoice.so i am using itextsharp.
but i am getting Index out of bound array at XMLWorkerHelper.
I am using itextsharp.xmlworker.dll, v5.4.5.0
when i try to update itextsharp.xmlworker.dll, v5.4.5.9
this code works fine..but all other modules of my project which use iTextsharp starts getting error.
if this is version problem, then how i add two different dll in bin folder and use it
or it is code related error?

EPPlus Array dimensions exceeded supported range. System.OutOfMemoryException

Ok so I am trying to load a CSVStream into an ExcelPackage (I am using EPPlus).
It always fails at line 221482, no matter what option I choose. I am running on x64 and I have in my app.config...
The error given is the one from the title :(
public ExcelPackage ExcelPackageFromCsvStream(Stream csvStream)
{
var excelPackage = new ExcelPackage();
var workSheet = excelPackage.Workbook.Worksheets.Add("Sheet1");
var csvFormat = new ExcelTextFormat
{
Delimiter = ',',
TextQualifier = '"',
DataTypes = new[] { eDataTypes.String }
};
using (var sr = new StreamReader(csvStream))
{
int i = 1;
foreach (var line in sr.ReadLines("\r\n"))
{
workSheet.Cells["A" + i].LoadFromText(line, csvFormat);
i++;
}
}
return excelPackage;
}
Resolved it by creating multiple ExcelPackages and also I've read the stream in batches (e.g. 200k lines at once)
public List<ExcelPackage> ExcelPackagesFromCsvStream(Stream csvStream, int batchSize)
{
var excelPackages = new List<ExcelPackage>();
int currentPackage = -1; // so that first package will have the index 0
var csvFormat = new ExcelTextFormat
{
Delimiter = ',',
TextQualifier = '"',
DataTypes = new[] {eDataTypes.String}
};
using (var sr = new StreamReader(csvStream))
{
int index = 1;
foreach (var line in sr.ReadLines("\r\n"))
{
if ((index - 1) % batchSize == 0)
{
var excelPackage = new ExcelPackage();
excelPackage.Workbook.Worksheets.Add("Sheet1");
excelPackages.Add(excelPackage);
currentPackage++;
index = 1;
}
excelPackages[currentPackage].Workbook.Worksheets.First().Cells["A" + index].LoadFromText(line, csvFormat);
index++;
}
}
return excelPackages;
}

Exception of type 'System.OutOfMemoryException' was thrown when writing data to excel

I am trying to write about 200000 lines into Excel and getting the error
Exception of type 'System.OutOfMemoryException' was thrown
My code is like below:
DataTable dtS = new DataTable();
dtS = myFucntion();
FileStream fs = new FileStream(Server.MapPath(#"~/Images/Tss_rpt.xlsx"),
FileMode.Open, FileAccess.Read);
NPOI.XSSF.UserModel.XSSFWorkbook PBLXSSFWorkbook2 =
new NPOI.XSSF.UserModel.XSSFWorkbook(fs);
XSSFSheet PBLsheet2 = (XSSFSheet)PBLXSSFWorkbook2.GetSheet("TssAML");
if (dtS.Rows.Count > 0)
{
XSSFRow PBLrows;
for (int i = 0; i < dtS.Rows.Count; i++)
{
PBLrows = (XSSFRow)PBLsheet2.CreateRow(i);
for (int j = 0; j < dtS.Columns.Count; j++)
{
PBLrows.CreateCell(j).SetCellValue(dtS.Rows[i][j].ToString());
}
}
PBLrows = null;
MemoryStream ms = new MemoryStream();
PBLXSSFWorkbook2.Write(ms);
ExportDataTableToExcel(ms, "Txn_Aml_rpt.xlsx");
}
else
{
clsMessageBox.Show("No Record(s) Found !!"); return;
}
Add
Response.Buffer = true;
Response.Clear();
before writing data.

SQL MDF Database every cell displays: "System.__ComObject"

When I execute this program the Excel part generates and string array: cellValue just fine.
When it inserts into the SQL MDF Database: MDFExcel every cell displays: "System.__ComObject".
How do you display the string value instead of the "System.__ComObject"?
protected void Button1_Click(Object sender, EventArgs e)
{
DataSet ds = new DataSet();
//From Excel
Microsoft.Office.Interop.Excel.Application exlApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook exlWb = exlApp.Workbooks.Open(#"C:\Users\Optiplex760\Documents\a Excel\ExcelToMDF.xls");
Microsoft.Office.Interop.Excel.Worksheet exlWs= exlWb.Sheets["Sheet1"];
Microsoft.Office.Interop.Excel.Range usedRange = exlWs.UsedRange;
int col = Convert.ToInt32(usedRange.Columns.Count);
int row = Convert.ToInt32(usedRange.Rows.Count);
exlApp.Visible = true;
string[,] cellValue = new string[row + 1, col + 1];
for (int j = 1; j <= row-1; j++)
{
for (int k = 1; k <= col-1; k++)
{
cellValue[j, k] = exlWs.Cells[j+1,k+1].ToString();
}
}
exlWb.Close();
exlWs = null;
exlWb = null;
exlApp.Quit();
exlApp = null;
//To MSSQL
String connStr, cmdStr;
connStr = ConfigurationManager.ConnectionStrings["MDFExceldb"].ConnectionString;
for (int h = 1; h<row; h++)
{
cmdStr = "INSERT INTO [Table1] (col1,col2,col3) VALUES (#col1,#col2,#col3);";
try
{
using (SqlConnection conn = new SqlConnection(connStr))
{
using (SqlCommand cmd = new SqlCommand(cmdStr, conn))
{
conn.Open();
cmd.Parameters.AddWithValue("#col1", cellValue[1, h]);
cmd.Parameters.AddWithValue("#col2", cellValue[2, h]);
cmd.Parameters.AddWithValue("#col3", cellValue[3, h]);
cmd.ExecuteNonQuery();
conn.Close();
cmd.Dispose();
conn.Dispose();
}
}
}
catch (Exception ex)
{
Label2.Text = ex.ToString();
}
}
}
Worksheet.Cells returns a Range and not a single value - and a Range (an RCW object) does not implemented a sensible ToString; thus it defaults to the "System.__ComObject" value shown.
Use the Text property of the Range, eg.
cellValue[j, k] = Convert.ToString(exlWs.Cells[j+1,k+1].Text);
While this should fix the immediate problem, it is also an inefficient process. See this response (using the Value/Value2 property) for how to access the Range values as a 2-dimensional array and reduce excessive range-slicing.

Validating a phone number using ASP.NET and the Twilio API

I'm trying to check whether numbers are valid using the code below. Will this work?
try
{
TwilioRest.Account account = new TwilioRest.Account(TwilioRest.TwilioConstants.ACCOUNT_SID, TwilioRest.TwilioConstants.ACCOUNT_TOKEN);
string strResponse = account.request(String.Format("/{0}/Accounts/{1}/OutgoingCallerIds", TwilioRest.TwilioConstants.API_VERSION, TwilioRest.TwilioConstants.ACCOUNT_SID), "GET");
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(strResponse);
XmlNode root = xmlDoc.DocumentElement.ChildNodes[0];
int cont = 0;
if (root.ChildNodes.Count > 0)
{
for (int i = 0; i < root.ChildNodes.Count; i++)
{
string ss = root.ChildNodes[i].SelectSingleNode("PhoneNumber").ChildNodes[0].Value;
if (phoneno.Trim() == ss)
{
cont = 1;
break;
}
}
}
if (cont == 0)
{
btnSubmit.Visible = true;
}
}
catch (TwilioRest.TwilioRestException ex)
{
mpValidatePhone.Show();
ucMsgPhone.MessageType = MessageType.Error;
ucMsgPhone.Text = TwilioErrorMessage(ex.ToString());
}
try like this....
string strResponse = account.request(String.Format("/{0}/Accounts/{1}/OutgoingCallerIds",
TwilioRest.TiwlioConstants.API_VERSION, TwilioRest.TiwlioConstants.ACCOUNT_SID), "GET");
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(strResponse);
XmlNode root = xmlDoc.DocumentElement.ChildNodes[0];
foreach (XmlNode node in xmlDoc.DocumentElement.ChildNodes[0])
{
string nodeVal = node.SelectSingleNode("PhoneNumber").ChildNodes[0].Value.ToString();
string fonVal = foneCountryCode + PhoneNumber.Replace("-", "");
//if (node.SelectSingleNode("PhoneNumber").ChildNodes[0].Value == "+" + PhoneNumber.Replace("-", ""))
if(nodeVal == fonVal)
{
result = true;
break;
}
}

Resources