How to format heading in excel / csv using C# - c#

My code will generate the excel document like this
|id | Name | Address | company_Name | Destination|
|----|-------|----------|--------------|------------|
|##1 | xxx | xxxx | xxx | xxxxx |
But I want like this...
-----------------------------------------------------
| Personal Information | Working INFO |
-----------------------------------------------------
|id | Name | Address | company_Name | Destination|
|----|-------|----------|--------------|------------|
|##1 | xxx | xxxx | xxx | xxxxx |
-----------------------------------------------------
I get the data from the API and I will save it using the SaveFileDialog
SaveFileDialog dialog = new SaveFileDialog();
dialog.Title = "Save file as...";
dialog.Filter = "Text files (*.csv)|*.csv";
dialog.RestoreDirectory = true;
if (dialog.ShowDialog() == DialogResult.OK)
{
System.IO.StreamWriter writer = new System.IO.StreamWriter(dialog.FileName); //open the file for writing.
writer.Write(report); //write the current date to the file. change this with your date or something.
writer.Close(); //remember to close the file again.
writer.Dispose(); //remember to dispose it from the memory.
program.ShowInformationMessage("File Save successfully");
}
There is no problem with it.
I want to make the heading as the inline something like it.

...
System.IO.StreamWriter writer = new System.IO.StreamWriter(dialog.FileName); //open the file for writing.
writer.Write("Personal Information" + delimiter + delimiter + "Working INFO" + delimiter);
writer.Write(report); //write the current date to the file. change this with your date or something.
...
Csv format doesn't support merged cells, but still you can arrange header line like described above. Just replace delimiter with whatever your cell delimiter is.

Have you considered using closedxml (https://closedxml.codeplex.com/).
var wb = new XLWorkbook(report); //open spreadsheet
IXLWorksheet ws = wb.Worksheets.First(); //get first sheet
ws.Row(1).InsertRowsAbove(1); //insert row
ws.Cell("A1").Value = "Personal Information";
ws.Cell("A4").Value = " Working INFO";
ws.Range("A1:A3").Row(1).Merge(); // merge first title
ws.Range("A4:A6").Row(1).Merge(); // merge second
wb.SaveAs(writer);
You can also open csv's and save as csv

Firstly create your excel file template in excel and format it as you want.
Put only one line where lots of rows will be printed.
Put labels into the data row to replace with real data.
Save it as MHT file. (styles will be saved, too like html)
Open the mht file with text editor.
Put < !#> at the begining and end of the data row so that you can split the file content from your program and populate real data lines dynamically by replacing your labels with real properties.
<!#>
<tr height=3D20 style=3D'height:15.0pt'>
<td height=3D20 class=3Dxl67 style=3D'height:15.0pt;border-top:none'>[id]=</td>
<td class=3Dxl67 style=3D'border-top:none;border-left:none'>[name]</td>
<td class=3Dxl67 style=3D'border-top:none;border-left:none'>[company<span style=3D'display:none'>]</span></td>
<td class=3Dxl67 style=3D'border-top:none;border-left:none'>[destination]=</td>
</tr>
<!#>
Save the file from text editor.
From your program, you will read the mht file content, you will split it with the < !#> and multiply the data row part, append all together and save to another file..thats it..

You need to have installed Microsoft Visual Studio Tools for Office.
After that create common .NET project and add the reference to COM object Microsoft.Office.Interop.Excel.dll via 'Add Reference..' dialog.
Application excel = new Application();
Workbook wb = excel.Workbooks.Open(path);
//Get All available worksheets
//Excel.Sheets excelSheets = wb.Worksheets;
//Get Specific WorkSheet
string currentSheet = "Sheet1";
Excel.Worksheet newSheet = (Excel.Worksheet)wb.get_Item(currentSheet);
newSheet.Cells[i, j].HorizontalAlignment = ExcelAlignment.xlLeft; //or Excel.XlHAlign.xlHAlignLeft

Related

saving data from c# to Excel crashes

I work on a project where I'd like to save some data in an Excel sheet,
Here is my code:
private void myButton11_Click(object sender, EventArgs e)
{
Microsoft.Office.Interop.Excel.Application excel;
Microsoft.Office.Interop.Excel.Workbook excelworkbook;
Microsoft.Office.Interop.Excel.Worksheet excelsheet;
excel = new Microsoft.Office.Interop.Excel.Application();
excel.Visible = false;
excel.DisplayAlerts = false;
excelworkbook = excel.Workbooks.Add(Type.Missing);
excelsheet = (Microsoft.Office.Interop.Excel.Worksheet)excelworkbook.ActiveSheet;
excelsheet.Name = "dataToExcel";
// fill in data
excelsheet.Cells[1, 1] = "test";
excelsheet.Cells[3, 3] = "test2";
// save excel
excelworkbook.SaveAs(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "//dataToExcel.xls",
Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal);
true, true, 1, 10, false);
}
The problem is when executing it crashes and shows me this error message:
System.Runtime.InteropServices.COMException
HResult=0x800A03EC
Message=Coudn't access file. Please try thoses options :
• Make sure the file exist.
• Make sure the file is not in read only.
• Make sure file path isn't containing thoses characteres: < > ? [ ] : | or *
• Make sure the file path and names do not take more than 218 caracteres.
C:\Users\corentin.boudaud\source\repos\FabLoop_project_V0.0.0\FabLoop_project_V0.0.0\Program.cs :ligne 20
The crash occurs on "SaveAs", the file I'm writing to is in my documents (public, write available)
Any idea where the problem might come from?
Thanks
You can save it easy as a .csv file. CSV is also a tabel and if you open it it will open in excel.
You can do this with System.IO
Thats a csv file in excel:
and thats a csv file in notepad++
I found the problem,
when using excelworkbook.SaveAs(), the path need to be using '\' to set the path and not '/'
I can then save the file as I want, .csv .xls or .xlsx

How to set active sheet with Open XML SDK 2.5

using the example here How to Copy a Worksheet within a Workbook
I have successfully been able to clone/copy sheets in my excel file, however when I open the excel the 2nd sheet is the active(visible) sheet. I haven't been able to locate a property that could do thins.....Is there any way to specify what sheet is active?
I've tried to force it by opening and editing the first sheet in the file thinking it was the last edited sheet that was active but that didn't work either.
any help would be great. TIA
update: looking at the workbook.xml created when renaming the .xlsx to .zip I came accross the 'activeTab' property. made a quick change to my code and seems to work just fine
public void SetFirstSheetInFocus(String xlsxFile)
{
using (SpreadsheetDocument spreadSheet = SpreadsheetDocument.Open(xlsxFile, true))
{
//Get a reference to access the main Workbook part, which contains all references
WorkbookPart _workbookPart = spreadSheet.WorkbookPart;
if (_workbookPart != null)
{
WorkbookView _workbookView = spreadSheet.WorkbookPart.Workbook.BookViews.ChildElements.First<WorkbookView>();
if (_workbookView != null)
{
_workbookView.ActiveTab = 0; // 0 for first or whatever tab you want to use
}
// Save the workbook.
_workbookPart.Workbook.Save();
}
}
}
If the name of your sheet is in the variable
sheetName
you can set the sheet with that name active like this:
using (var spreadsheetDoc = SpreadsheetDocument.Open(emptyHIPTemplatePath, true /* isEditable */, new OpenSettings { AutoSave = false }))
{
var workbookPart = spreadsheetDoc.WorkbookPart;
var workBook = spreadsheetDoc.WorkbookPart.Workbook;
var sheet = workBook.Descendants<Sheet>().FirstOrDefault(s => s.Name == sheetName);
var sheetIndex = workBook.Descendants<Sheet>().ToList().IndexOf(sheet);
var workBookView = workBook.Descendants<WorkbookView>().First();
workBookView.ActiveTab = Convert.ToUInt32(sheetIndex);
...
workBook.Save();
}
From Vincent Tan's book:
The SheetId property doesn't determine the order. The order of
appending the Sheet classes to the Sheets class, does.
When you add a sheet, it gets the next index, but a single sheet does not have an index. OpenXML gives it an index when you are done adding sheets. Again, from Vincent Tan's book:
Let's say you have 3 worksheets named Sheet1, Sheet2 and Sheet3.
However, when you appended the corresponding Sheet classes, you did it
as Sheet2, Sheet3 and Sheet1, in that order.

mso-data-placement:same-cell not working

I am exporting data into Excel from a web page. This should be a no brainer, but there are <p> tags in the data. This causes Excel to create new rows when the data should all be in the same cell. After some research I found that mso-data-placement should do the trick, but it's not working. Excel opens, the data is displayed, but extra uncessary rows are created. Here is the code I use to export the data:
protected void doexcel()
{
string style = #"<style type='text/css'>P {mso-data-placement:same-cell; font-weight:bold;}</style>";
HttpResponse response = HttpContext.Current.Response;
// first let's clean up the response.object
response.Clear();
response.Charset = "";
//set the response mime type for excel
response.ContentType = "application/vnd.ms-excel";
Random RandomClass = new Random();
int RandomNumber = RandomClass.Next();
String filename = "a" + RandomNumber + DateTime.Now + ".xls";
response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"" );
// create a string writer
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
HttpContext.Current.Response.Write(style);
SqlDataSourceEmployeeAssets.ConnectionString = MyObjects.Application.CurrentContext.ConnectionString;
String sql = (string)Session["sql"];
SqlDataSourceEmployeeAssets.SelectCommand = sql;
// lCount.Text = "Query returned " + getCount(query) + " rows.";
DataGrid dge = new DataGrid();
dge.DataSource = SqlDataSourceEmployeeAssets;
dge.DataBind();
dge.RenderControl(htw);
response.Write(sw.ToString());
response.End();
}
}
}
This is an example of the raw data in the database that is giving me grief:
<P>4/13/2011 : Cheng "Jonathan" Vaing is with BSES Graffiti Unit.</P><P>4/13/2011 : Cheng "Jonathan" Vaing is with</P>
Suggestions?
I tried a couple of other things
I went straight to the data and added the mso-data-placement attribute to the paragraph tag inline. Still didn't work. The data looked like this
<P style="mso-data-placement:same-cell> my data </p>
I tried other mso-* attributes, that didn't work either. For example, I changed my stylesheet to look like this
<style type='text/css'>P {mso-highlight:yellow}</style>";
Why oh why doesn't Excel recognize my mso-* attributes?!?!
There is a solution but it is not clean.
After the dge.DataBind, place the following code. This will encode the text of each cell
foreach (DataGridItem dgi in dge.Items)
{
foreach (TableCell cell in dgi.Cells)
{
cell.Text = WebUtility.HtmlEncode(cell.Text);;
}
}
The Excel file, when opened, should show the raw data with the markup, all in one cell.
I found that this works because Excel actually encodes the text, as well. To see what Excel does in action, do the following:
Create a new workbook in Excel (I am using Office 2013).
In the first cell, paste the raw data (as you have it displayed). Do this by first pressing F2 (insert into cell), then paste the text.
Save the workbook as an HTML file (or web page).
Using windows explorer, go to the folder location of where you saved the file. There should be a hidden folder (i think it is hidden) with the same name as your file. For example, if your workbook is Book1.htm, there should be a folder labeled Book1_files.
In this folder, there should be an HTM file with the name sheet001.htm. Open this file in notepad (or any text editor...not excel or word)
Locate your raw data. You will see that the text is not showing the HTML markup, rather it is showing the encoded version.
Hope this helps.

load an adobe dynamic form file

I have a .pdf created through Adobe LiveCycle Designer (it's a dynamic pdf ) i want to add this pdf to my windows app
this is what i tried
File file1 = new File(fileName);
System.Xml.XmlDocument xfadoc = new System.Xml.XmlDocument();
xfadoc.LoadXml(fileName);
here's how i get filename
OpenFileDialog dialog = new OpenFileDialog();
dialog.InitialDirectory = "c:\\";
dialog.Filter = "pdf files (*.pdf) | *.pdf | All Files (*.*) | *.* | xdp files (*.xdp) | *.xdp ";
dialog.FilterIndex = 2;
dialog.RestoreDirectory = true;
dialog.CheckFileExists = true;
dialog.DefaultExt = "pdf | xdp";
fileName = dialog.FileName.ToString();
but when i click on open file button and browse to where i have stored it ; it doesnot even appear
Also when i try to load this file in my C# windows app it gives me an exception at the following line
xfadoc.LoadXml(fileName);
the exception says that
'Data at root level is invalid'
If i say that i have loaded the string (filepath name) someone please tell me how can i extract the xml part only form this dynamic file
Try Filter without spaces in extensions part.
dialog.Filter = "pdf files (*.pdf)|*.pdf|All Files (*.*)|*.*|xdp files (*.xdp)|*.xdp";
LoadXml loads the document from the string parameter. You want to use the Load method.

Export data from DataTable to Excel file

I have DataTable object. How can I export it into an XLS file?
I tried to render it via DataGrid
DataGrid dgGrid = new DataGrid();
dgGrid.DataSource = dt;
dgGrid.DataBind();
dgGrid.RenderControl(hw);
but the file is very large and the OutOfMemoryException appears.
I can use http://epplus.codeplex.com/.
I need C# function.
There are a number of options, one of them being the Access OLE DB Provider which also operates in terms of DataTables.
If you want more fine-grained support over the document, I'd recommend the Open XML SDK 2.0, whixh is .xmlx only.
For raw data, I think that Access OLE DB (also reffered to as the ACE provider) is the best choice since it enables a database-like experience. Open XML assumes fairly good knowledge of XML and the willingnes to experiment a bit more. On the other hand, you can apply formatting, add formulas and other advanced features.
Ok, find a solution here: http://bytesofcode.hubpages.com/hub/Export-DataSet-and-DataTable-to-Excel-2007-in-C
Just download epplus library and call method:
private void GenerateExcel(DataTable dataToExcel, string excelSheetName)
{
string fileName = "ByteOfCode";
string currentDirectorypath = Environment.CurrentDirectory;
string finalFileNameWithPath = string.Empty;
fileName = string.Format("{0}_{1}", fileName, DateTime.Now.ToString("dd-MM-yyyy"));
finalFileNameWithPath = string.Format("{0}\\{1}.xlsx", currentDirectorypath, fileName);
//Delete existing file with same file name.
if (File.Exists(finalFileNameWithPath))
File.Delete(finalFileNameWithPath);
var newFile = new FileInfo(finalFileNameWithPath);
//Step 1 : Create object of ExcelPackage class and pass file path to constructor.
using (var package = new ExcelPackage(newFile))
{
//Step 2 : Add a new worksheet to ExcelPackage object and give a suitable name
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(excelSheetName);
//Step 3 : Start loading datatable form A1 cell of worksheet.
worksheet.Cells["A1"].LoadFromDataTable(dataToExcel, true, TableStyles.None);
//Step 4 : (Optional) Set the file properties like title, author and subject
package.Workbook.Properties.Title = #"This code is part of tutorials available at http://bytesofcode.hubpages.com";
package.Workbook.Properties.Author = "Bytes Of Code";
package.Workbook.Properties.Subject = #"Register here for more http://hubpages.com/_bytes/user/new/";
//Step 5 : Save all changes to ExcelPackage object which will create Excel 2007 file.
package.Save();
MessageBox.Show(string.Format("File name '{0}' generated successfully.", fileName)
, "File generated successfully!", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
First of all, Google is your best friend. Also you can search on this site.
Some solutions:
You can write an excel file with SQL.
You can use the reference to Microsoft Office library to create an excel file
You can write an XML file.

Categories