I have been working on Excel Sheet Formatting using EPPlus. I am able to create group when the Excel Sheet is in a ordered one .But if the input comes unordered and I have to group then I am facing issue.
The Excel input looks like in the problematic sceario:
Field1 Field2 Field3
1 XYZ ABC
3.1 PRQ SDE
1.1 AB ST
1.2 MN RT
like wise and all 1 related row should be at one group like in ascending order.
I have written the below which if sorted works fine but not able to figure out if the input is jumbled up/ not sorted.
Here is my code.
Thanks for your help.
namespace EPPlusTestDemo {
class Program
{
static void Main(string[] args)
{
// Set the File name and get the output directory
var fileName = "Example-File-" + DateTime.Now.ToString("yyyy-MM-dd--hh-mm-ss") + ".xlsx";
var outputDir = #"C:\Users\asder\Desktop\outpath\" + fileName;
// Create the file using the FileInfo object
var file = new FileInfo(outputDir);
using (var package = new ExcelPackage(file))
{
// Adding a new worksheet to the empty workbook
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Example list - " + DateTime.Now.ToShortDateString());
// --------- Data and styling goes here -------------- //
// Header part
worksheet.Cells["A1"].Value = "Field1";
worksheet.Cells["B1"].Value = "Field2";
worksheet.Cells["C1"].Value = "Field3";
worksheet.Cells["D1"].Value = "Field4";
worksheet.Cells["E1"].Value = "Field5";
worksheet.Cells["A1:E1"].Style.Font.Bold = true;
// The row number
int initialRowNum = 2;
int rowNumber = initialRowNum;
#region input_toExcel
// Filling the data from the 2nd row of the excel sheet
worksheet.Cells[rowNumber, 1].Value = "1";
worksheet.Cells[rowNumber, 2].Value = "GRP";
worksheet.Cells[rowNumber, 3].Value = "ABC";
worksheet.Cells[rowNumber, 4].Value = "CDE";
worksheet.Cells[rowNumber, 5].Value = "ABCD";
rowNumber++;
worksheet.Cells[rowNumber, 1].Value = "1.1";
worksheet.Cells[rowNumber, 2].Value = "Item";
worksheet.Cells[rowNumber, 3].Value = "ABC";
worksheet.Cells[rowNumber, 4].Value = "CDE";
worksheet.Cells[rowNumber, 5].Value = "ABCD";
rowNumber++;
worksheet.Cells[rowNumber, 1].Value = "1.2";
worksheet.Cells[rowNumber, 2].Value = "Item";
worksheet.Cells[rowNumber, 3].Value = "ABC";
worksheet.Cells[rowNumber, 4].Value = "CDE";
worksheet.Cells[rowNumber, 5].Value = "ABCD";
rowNumber++;
worksheet.Cells[rowNumber, 1].Value = "1.3";
worksheet.Cells[rowNumber, 2].Value = "Item";
worksheet.Cells[rowNumber, 3].Value = "ABC";
worksheet.Cells[rowNumber, 4].Value = "CDE";
worksheet.Cells[rowNumber, 5].Value = "ABCD";
rowNumber++;
worksheet.Cells[rowNumber, 1].Value = "1.4";
worksheet.Cells[rowNumber, 2].Value = "Item";
worksheet.Cells[rowNumber, 3].Value = "ABC";
worksheet.Cells[rowNumber, 4].Value = "CDE";
worksheet.Cells[rowNumber, 5].Value = "ABCD";
rowNumber++;
worksheet.Cells[rowNumber, 1].Value = "2";
worksheet.Cells[rowNumber, 2].Value = "GRP";
worksheet.Cells[rowNumber, 3].Value = "ABC";
worksheet.Cells[rowNumber, 4].Value = "CDE";
worksheet.Cells[rowNumber, 5].Value = "ABCD";
rowNumber++;
worksheet.Cells[rowNumber, 1].Value = "2.1";
worksheet.Cells[rowNumber, 2].Value = "Item";
worksheet.Cells[rowNumber, 3].Value = "ABC";
worksheet.Cells[rowNumber, 4].Value = "CDE";
worksheet.Cells[rowNumber, 5].Value = "ABCD";
rowNumber++;
worksheet.Cells[rowNumber, 1].Value = "2.2";
worksheet.Cells[rowNumber, 2].Value = "Item";
worksheet.Cells[rowNumber, 3].Value = "ABC";
worksheet.Cells[rowNumber, 4].Value = "CDE";
worksheet.Cells[rowNumber, 5].Value = "ABCD";
rowNumber++;
worksheet.Cells[rowNumber, 1].Value = "2.3";
worksheet.Cells[rowNumber, 2].Value = "Item";
worksheet.Cells[rowNumber, 3].Value = "ABC";
worksheet.Cells[rowNumber, 4].Value = "CDE";
worksheet.Cells[rowNumber, 5].Value = "ABCD";
rowNumber++;
worksheet.Cells[rowNumber, 1].Value = "2.4";
worksheet.Cells[rowNumber, 2].Value = "Item";
worksheet.Cells[rowNumber, 3].Value = "ABC";
worksheet.Cells[rowNumber, 4].Value = "CDE";
worksheet.Cells[rowNumber, 5].Value = "ABCD";
#endregion
// Grouping after comparing the Cell Value
for ( var rowIndex = initialRowNum; worksheet.Row(rowIndex) != null; rowIndex++)
{
// Checking for NULL in the Excel Sheet
var comapreable = worksheet.Cells[rowIndex, 1].GetValue<string>();
// Group Counter
int count = 0;
if (comapreable != null)
{
Regex regexIntegral = new Regex(#"\d");
Match matchIntegral = regexIntegral.Match(comapreable);
Regex regexDouble = new Regex(#"([1-9]+)\.([1-9]+)");
Match matchDouble = regexDouble.Match(comapreable);
// Checking if the Cell of the Excel sheet contains any integral value
if ( matchIntegral.Success == true )
{
count++; // Incrementing the Group Level Counter
// Checking if the Cell contains the decimal values
if ( matchDouble.Success == true )
{
worksheet.Row(rowIndex).OutlineLevel = count;
worksheet.Row(rowIndex).Collapsed = true;
}
}
}
else
{
break;
}
}
// Saving the File
package.Save();
}
// Console.ReadKey();
}
} }
I have found out the below findings on my question.Please find the code below.
Please do comment if you feel there are more good solutions. Thanks
class Program
{
static void Main(string[] args)
{
// Set the File name and get the output directory
var fileName = "Example-File-" + DateTime.Now.ToString("yyyy-MM-dd--hh-mm-ss") + ".xlsx";
var outputDir = #"E:\C#Programming\ExcelFormattingProject\outpath\" + fileName;
DataTable dt = new DataTable();
// Create the file using the FileInfo object
var file = new FileInfo(outputDir);
using (var package = new ExcelPackage(file))
{
// Adding a new worksheet to the empty workbook
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Example list - " + DateTime.Now.ToShortDateString());
// --------- Data and styling goes here -------------- //
// Header part
worksheet.Cells["A1"].Value = "Field1";
worksheet.Cells["B1"].Value = "Field2";
worksheet.Cells["C1"].Value = "Field3";
worksheet.Cells["D1"].Value = "Field4";
worksheet.Cells["E1"].Value = "Field5";
worksheet.Cells["A1:E1"].Style.Font.Bold = true;
// The row number
int initialRowNum = 2;
int rowNumber = initialRowNum;
#region input_toExcel
// Filling the data from the 2nd row of the excel sheet
worksheet.Cells[rowNumber, 1].Value = "1";
worksheet.Cells[rowNumber, 2].Value = "GRP";
worksheet.Cells[rowNumber, 3].Value = "ABC";
worksheet.Cells[rowNumber, 4].Value = "CDE";
worksheet.Cells[rowNumber, 5].Value = "ABCD";
rowNumber++;
worksheet.Cells[rowNumber, 1].Value = "2.1";
worksheet.Cells[rowNumber, 2].Value = "Item2.1";
worksheet.Cells[rowNumber, 3].Value = "ABC";
worksheet.Cells[rowNumber, 4].Value = "CDE";
worksheet.Cells[rowNumber, 5].Value = "ABCD";
rowNumber++;
worksheet.Cells[rowNumber, 1].Value = "1.2";
worksheet.Cells[rowNumber, 2].Value = "Item1.2";
worksheet.Cells[rowNumber, 3].Value = "ABC";
worksheet.Cells[rowNumber, 4].Value = "CDE";
worksheet.Cells[rowNumber, 5].Value = "ABCD";
rowNumber++;
worksheet.Cells[rowNumber, 1].Value = "1.3";
worksheet.Cells[rowNumber, 2].Value = "Item";
worksheet.Cells[rowNumber, 3].Value = "ABC";
worksheet.Cells[rowNumber, 4].Value = "CDE";
worksheet.Cells[rowNumber, 5].Value = "ABCD";
rowNumber++;
worksheet.Cells[rowNumber, 1].Value = "1.4";
worksheet.Cells[rowNumber, 2].Value = "Item";
worksheet.Cells[rowNumber, 3].Value = "ABC";
worksheet.Cells[rowNumber, 4].Value = "CDE";
worksheet.Cells[rowNumber, 5].Value = "ABCD";
rowNumber++;
worksheet.Cells[rowNumber, 1].Value = "2";
worksheet.Cells[rowNumber, 2].Value = "GRP";
worksheet.Cells[rowNumber, 3].Value = "ABC";
worksheet.Cells[rowNumber, 4].Value = "CDE";
worksheet.Cells[rowNumber, 5].Value = "ABCD";
rowNumber++;
worksheet.Cells[rowNumber, 1].Value = "1.1";
worksheet.Cells[rowNumber, 2].Value = "Item";
worksheet.Cells[rowNumber, 3].Value = "ABC";
worksheet.Cells[rowNumber, 4].Value = "CDE";
worksheet.Cells[rowNumber, 5].Value = "ABCD";
rowNumber++;
worksheet.Cells[rowNumber, 1].Value = "2.2";
worksheet.Cells[rowNumber, 2].Value = "Item";
worksheet.Cells[rowNumber, 3].Value = "ABC";
worksheet.Cells[rowNumber, 4].Value = "CDE";
worksheet.Cells[rowNumber, 5].Value = "ABCD";
rowNumber++;
worksheet.Cells[rowNumber, 1].Value = "2.3";
worksheet.Cells[rowNumber, 2].Value = "Item";
worksheet.Cells[rowNumber, 3].Value = "ABC";
worksheet.Cells[rowNumber, 4].Value = "CDE";
worksheet.Cells[rowNumber, 5].Value = "ABCD";
rowNumber++;
worksheet.Cells[rowNumber, 1].Value = "2.4";
worksheet.Cells[rowNumber, 2].Value = "Item";
worksheet.Cells[rowNumber, 3].Value = "ABC";
worksheet.Cells[rowNumber, 4].Value = "CDE";
worksheet.Cells[rowNumber, 5].Value = "ABCD";
#endregion
// Need to fetch the data as a row or recorset and then sort it and place it to a new Excel
//worksheet.Cells["A2:A11"].Style.Numberformat.Format = "#0\\.00";
for (var rowIndex = 1;rowIndex < 11; rowIndex++)
{
var colIndex = 1;
for (; colIndex <= 5;)
{
// Filling the First Row of the DataTable with the Field Name as on the Excel Sheet
if (rowIndex == 1)
{
dt.Columns.Add(new DataColumn(worksheet.Cells[rowIndex, colIndex].Text));
}
else
{
dt.Columns.Add(new DataColumn());
}
colIndex++;
}
dt.Rows.Add(dt.NewRow());
}
// Inserting Values in the DataTable
for (var rowIndex = 1; rowIndex < 11; rowIndex++)
{
// Filling the DataTable with Excel Contents
for (var colIndex = 1; colIndex <= 5;)
{
dt.Rows[rowIndex - 1][colIndex - 1] = worksheet.Cells[rowIndex+1, colIndex].Text;
colIndex++;
}
}
// Sorting the DataTable
DataTable dtOut = null;
dt.DefaultView.ToTable(false, "Field1", "Field2", "Field3", "Field4", "Field5");
dt.DefaultView.Sort = "Field1";
dtOut = dt.DefaultView.ToTable(false, "Field1", "Field2","Field3","Field4","Field5");
// Exporting the DataTable to the WorkSheet of the Excel
worksheet.Cells["A1"].LoadFromDataTable(dtOut, true);
#endregion
// Grouping after comparing the Cell Value
for ( var rowIndex = 2; worksheet.Row(rowIndex) != null; rowIndex++)
{
// Checking for NULL in the Excel Sheet
var comapreable = worksheet.Cells[rowIndex, 1].GetValue<string>();
// Group Counter
int count = 0;
if (comapreable != null)
{
Regex regexIntegral = new Regex(#"\d");
Match matchIntegral = regexIntegral.Match(comapreable);
Regex regexDouble = new Regex(#"([1-9]+)\.([1-9]+)");
Match matchDouble = regexDouble.Match(comapreable);
// Checking if the Cell of the Excel sheet contains any integral value
if ( matchIntegral.Success == true )
{
count++; // Incrementing the Group Level Counter
// Checking if the Cell contains the decimal values
if ( matchDouble.Success == true )
{
worksheet.Row(rowIndex).OutlineLevel = count;
worksheet.Row(rowIndex).Collapsed = true;
}
}
}
else
{
break;
}
}
// Saving the File
package.Save();
}
// Console.ReadKey();
}
}
Related
This question already has answers here:
Download Excel file via AJAX MVC
(15 answers)
How to download excel using ajax call?
(1 answer)
Closed 2 years ago.
I have a list of items from the database base that I will like to generate in excel and PDF. I want to do the excel first. I have not done this before, following a tutorial online I was able to get it to return FIle. But the problem is that I got "non invocable member 'File" cannot be used like a method". I have already used "using System.IO;"
Can someone help figure out what I am doing wrong
{
try
{
//var parameters = new { UserName = username, Password = password };
//var sql = "select * from users where username = #UserName and password = #Password";
//var result = connection.Query(sql, parameters);
IEnumerable<DailyInterest> dailyInterests = null;
var Id = id;
using (var conn = new SqlConnection(connectionstring))
{
await conn.OpenAsync();
//var parameters = new { Id = id };
dailyInterests = conn.Query<DailyInterest>("Select * from DailyInterest where LoanAccountNo=#Id", new { Id = id });
//step1: create array to holder header labels
string[] col_names = new string[]{
"Loan Account No",
"Transaction Amount",
"Interest Rate",
"Interest Amount",
"Original Loan Amount",
"Narration",
"DRCR",
"Transaction Date"
};
//step2: create result byte array
byte[] result;
//step3: create a new package using memory safe structure
using (var package = new ExcelPackage())
{
//step4: create a new worksheet
var worksheet = package.Workbook.Worksheets.Add("final");
//step5: fill in header row
//worksheet.Cells[row,col]. {Style, Value}
for (int i = 0; i < col_names.Length; i++)
{
worksheet.Cells[1, i + 1].Style.Font.Size = 14; //font
worksheet.Cells[1, i + 1].Value = col_names[i]; //value
worksheet.Cells[1, i + 1].Style.Font.Bold = true; //bold
//border the cell
worksheet.Cells[1, i + 1].Style.Border.BorderAround(OfficeOpenXml.Style.ExcelBorderStyle.Thin);
//set background color for each sell
worksheet.Cells[1, i + 1].Style.Fill.PatternType = ExcelFillStyle.Solid;
worksheet.Cells[1, i + 1].Style.Fill.BackgroundColor.SetColor(Color.FromArgb(255, 243, 214));
}
int row = 8;
//step6: loop through query result and fill in cells
foreach (var item in dailyInterests)
{
for (int col = 1; col <= 2; col++)
{
worksheet.Cells[row, col].Style.Font.Size = 12;
//worksheet.Cells[row, col].Style.Font.Bold = true;
worksheet.Cells[row, col].Style.Border.BorderAround(OfficeOpenXml.Style.ExcelBorderStyle.Thin);
}
//set row,column data
worksheet.Cells[row, 1].Value = item.LoanAccountNo;
worksheet.Cells[row, 2].Value = item.TranAmount;
worksheet.Cells[row, 3].Value = item.InterestRatePerDay;
worksheet.Cells[row, 4].Value = item.AmountPerDay;
worksheet.Cells[row, 5].Value = item.OriginalLoanAmount;
worksheet.Cells[row, 6].Value = item.Narration;
worksheet.Cells[row, 7].Value = item.DRCR;
worksheet.Cells[row, 8].Value = item.TranDate;
//toggle background color
//even row with ribbon style
if (row % 8 == 0)
{
worksheet.Cells[row, 1].Style.Fill.PatternType = ExcelFillStyle.Solid;
worksheet.Cells[row, 1].Style.Fill.BackgroundColor.SetColor(Color.FromArgb(154, 211, 157));
worksheet.Cells[row, 2].Style.Fill.PatternType = ExcelFillStyle.Solid;
worksheet.Cells[row, 2].Style.Fill.BackgroundColor.SetColor(Color.FromArgb(154, 211, 157));
}
row++;
}
//step7: auto fit columns
worksheet.Cells[worksheet.Dimension.Address].AutoFitColumns();
//step8: convert the package as byte array
result = package.GetAsByteArray();
}
//step9: return byte array as a file
**//This is where the error is**
return File(result, "application/vnd.ms-excel", "test.xls");
}
}
catch (Exception ex)
{
throw ex;
}
}
I am using the EPPlus library to read a datetime value from a sql table and export it to excel. The export works fine but when I view the excel file the date shows as a double instead of dateime I have placed my code below
workSheet.Row(1).Height = 20;
workSheet.Row(1).Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
workSheet.Row(1).Style.Font.Bold = true;
workSheet.Cells[1, 1].Value = "UploadId";
workSheet.Cells[1, 2].Value = "ClientId";
workSheet.Cells[1, 3].Value = "Email1";
workSheet.Cells[1, 4].Value = "Email2";
workSheet.Cells[1, 5].Value = "Email3";
workSheet.Cells[1, 6].Value = "Email4";
workSheet.Cells[1, 7].Value = "DateStamp";
//Body of table
//
int recordIndex = 2;
foreach (var exportData in dataToExport)
{
//double date = double.Parse(date);
//string sDate = (workSheet.Cells[recordIndex, 7]).Value.ToString();
//double date = double.Parse(sDate);
//var dateTime = DateTime.FromOADate(date).ToString("MMMM dd, yyyy");
workSheet.Cells[recordIndex, 1].Value = UploadId;
workSheet.Cells[recordIndex, 2].Value = exportData.ClientId;
workSheet.Cells[recordIndex, 3].Value = exportData.Email1;
workSheet.Cells[recordIndex, 4].Value = exportData.Email2;
workSheet.Cells[recordIndex, 5].Value = exportData.Email3;
workSheet.Cells[recordIndex, 6].Value = exportData.Email4;
workSheet.Cells[recordIndex, 7].Value = exportData.DateStamp;
recordIndex++;
}
Something like this should do it;
workSheet.Cells[recordindex, 7].Style.Numberformat.Format = "yyyy-MM-dd";
What should I write to see images that coming from database in all rows
I want to see the image in [i,2] row.
Here is my code
int i = 2;
foreach (var item in chartProduct)
{
ws.Cells[i, 1].Value = item.Id;
ws.Cells[i, 1].Style.Font.Bold = true;
ws.Cells[i, 1].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
string imagePath = _hostingEnvironment.WebRootPath + $#"\images\product\" + item.ImageUrl;
FileInfo img = new FileInfo(imagePath);
ExcelPicture pic = ws.Drawings.AddPicture("img", img);
pic.SetSize(50,50);
ws.cells[i,2].value = ??
ws.Cells[i, 3].Value = item.Material.Code;
ws.Cells[i, 3].Style.Font.Bold = true;
ws.Cells[i, 3].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
ws.Cells[i, 4].Value = item.Material.Name;
ws.Cells[i, 4].Style.Font.Bold = true;
ws.Cells[i, 4].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
ws.Cells[i, 5].Value = item.Code;
ws.Cells[i, 5].Style.Font.Bold = true;
ws.Cells[i, 5].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
ws.Cells[i, 6].Value = item.Name;
ws.Cells[i, 6].Style.Font.Bold = true;
ws.Cells[i, 6].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
i++;
}
in this part what should i do ??
string imagePath = _hostingEnvironment.WebRootPath + $#"\images\product\" + item.ImageUrl;
FileInfo img = new FileInfo(imagePath);
ExcelPicture pic = ws.Drawings.AddPicture("img", img);
pic.SetSize(50,50);
ws.cells[i,2].value = ??
Try this solution,Hope It helps.
int i = 2;
foreach (var item in chartProduct)
{
ws.Cells[i, 1].Value = item.Id;
ws.Cells[i, 1].Style.Font.Bold = true;
ws.Cells[i, 1].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
ws.Column(2).Width = 50;
ws.Row(i).Height = 50;
// string imagePath = _hostingEnvironment.WebRootPath +
//$#"\images\product\" + item.ImageUrl;
string filePath= "~/images/product/" + item.ImageUrl;
AddPictures(ws, filePath,i,2);
ws.Cells[i, 3].Value = item.Material.Code;
ws.Cells[i, 3].Style.Font.Bold = true;
ws.Cells[i, 3].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
ws.Cells[i, 4].Value = item.Material.Name;
ws.Cells[i, 4].Style.Font.Bold = true;
ws.Cells[i, 4].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
ws.Cells[i, 5].Value = item.Code;
ws.Cells[i, 5].Style.Font.Bold = true;
ws.Cells[i, 5].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
ws.Cells[i, 6].Value = item.Name;
ws.Cells[i, 6].Style.Font.Bold = true;
ws.Cells[i, 6].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
i++;
}
separate method to add Picture
public void AddPictures(ExcelWorksheet ws, string filePath,int row,int col)
{
Image image = Image.FromFile(filePath);
OfficeOpenXml.Drawing.ExcelPicture pic =ws.Drawings.AddPicture(string.Format("Pic{0}",row), image);
pic.SetPosition(row-1, 0,0,0);
pic.SetSize(50,50);
}
foreach (var item in bh)
{
worksheet.Cells[rowNumber, 1].Value = item.bill_number;
worksheet.Cells[rowNumber, 2].Value = item.yearref + #"\" + item.monthref;
worksheet.Cells[rowNumber, 3].Value = item.stdate.ToShortDateString();
worksheet.Cells[rowNumber, 4].Value = item.enddate.ToShortDateString();
worksheet.Cells[rowNumber, 5].Value = item.duration;
worksheet.Cells[rowNumber, 6].Value = item.last_reading;
worksheet.Cells[rowNumber, 7].Value = item.new_reading;
worksheet.Cells[rowNumber, 8].Value = item.usage;
worksheet.Cells[rowNumber, 9].Value = item.totaldueamt;
worksheet.Cells[rowNumber, 10].Value = item.total_paid;
worksheet.Cells[rowNumber, 11].Value = item.paid_date.ToShortDateString(); }
I have the above code that loops through an SQL resultset which is later used to export to Excel, when the item.paid_date is null, in the exported Excel sheet the date is shown as 01/01/1900, How can I replace item.paid_date with '' if date is null?
Here is the store procedure, at times there won't be any record in the reading table where where bg.bill_number = p.bill_number
CREATE PROCEDURE [dbo].[BillHistory] #accNo varchar(50) as begin select bg.Id, bg.account_number, bg.bill_number, bg.year, bg.month, bg.usagetotal, bg.fineamt, bg.fuelcharge, bg.othercharge, bg.totalamt, bg.totaldueamt, bg.billdate, bg.bill_due_date, bg.outstanding_amt, bg.[desc], readingId = re.Id, re.accountno, re.oldccountNo, re.new_reading, re.last_reading, re.meterno, re.yearref , re.monthref , re.referencecount, re.stdate, re.enddate, current_reading_date = re.created_on, pre_reading_date = isnull((select top 1 c.created_on from reading c where c.accountno = #accNo and c.Id < re.Id order by c.Id desc),CAST(-53690 as datetime)), re.duration, re.usage, re.averageusage, re.averageconsumption, isnull((select p.total_paid from payment p where bg.bill_number = p.bill_number ),0) as total_paid, isnull((select p.created_on from payment p where bg.bill_number = p.bill_number ),0) as paid_date from reading re join billing_gen bg on re.Id=bg.reading_id where re.accountno = #accNo and bg.enable=1 order by bg.Id asc; end;
have you tried:
worksheet.Cells[rowNumber, 11].Value = item.paid_date == null ? string.Empty : item.paid_date.ToShortDateString();
?
I want to name each column in the first row of the excel sheet, I get an exception on the first line of naming the columns. Please advise?
Microsoft.Office.Interop.Excel.Application xla = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook wb = xla.Workbooks.Add(Microsoft.Office.Interop.Excel.XlSheetType.xlWorksheet);
Microsoft.Office.Interop.Excel.Worksheet ws = (Microsoft.Office.Interop.Excel.Worksheet)xla.ActiveSheet;
int i = 2;
int j = 1;
if (comboBox1.Text == "Brickcom")
{
try
{
ws.Rows[j, 1] = "Category";
ws.Rows[j, 2] = "Part Number";
ws.Rows[j, 3] = "TradePrice";
ws.Rows[j, 4] = "Product";
ws.Rows[j, 5] = "Resolution";
ws.Rows[j, 6] = "Included Accessories";
ws.Rows[j, 7] = "Major Acc Price";
foreach (ListViewItem comp in listView1.Items)
{
ws.Cells[i, j] = comp.Text.ToString();
foreach (ListViewItem.ListViewSubItem drv in comp.SubItems)
{
ws.Cells[i, j] = drv.Text.ToString();
j++;
}
j = 1;
i++;
}
xla.Visible = true;
}
catch
{
MessageBox.Show("Export did not work");
}
}
Try this:
ws.Cells[j, 1] = "Category";
ws.Cells[j, 2] = "Part Number";
ws.Cells[j, 3] = "TradePrice";
...
i would use stream writer :
SaveFileDialog savefile = new SaveFileDialog();
savefile.Filter = "CSV|*.csv";
savefile.RestoreDirectory = true;
savefile.ShowDialog();
string filename = savefile.FileName;
if (filename != "")
{
StreamWriter ofile = new StreamWriter(filename);
ofile.WriteLine("Category, Part Number, TradePrice, ..."); //just separate using a comma ,
//your complete writings here
ofile.Close(); //close the streamwriter and you're done
}
good luck