Convert datatable to excel 2007(.xlsx) - c#

I have an DataTable I need to put into Excel 2007 format and save it as an excel file(.xlsx) 2007.
Can anyone help me to achieve this?

You can use an OLEDB data provider and just treat Excel as another ADO.NET data source in order to loop through your DataTable rows and insert them into the Excel spreadsheet. Here's a Microsoft KB article that walks you through a lot of the details.
http://support.microsoft.com/kb/316934/en-us
The big thing to keep in mind is that you can create workbooks and sheets within the workbook, and you can reference existing sheets by appending a '$' at the end of the name. If you omit the '$' at the end of the sheet name, the OLEDB provider will assume that it's a new sheet and will try to create it.
The dollar sign following the
worksheet name is an indication that
the table exists. If you are creating
a new table, as discussed in the
Create New Workbooks and Tables
section of this article, do not use
the dollar sign.
You can create and spreadsheet in 2003 (.xls) or 2007 format (xlsx), and that's defined on your connection string -- you specify the file that you're going to write to, and just specify the extension. Make sure you use the right OLEDB provider version.
If you want to create a 2003 (.xls) version, you use this connection string:
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Book1.xls;Extended Properties="Excel 8.0;HDR=YES
If you want to create a 2007 (.xlsx) version, you use this connection string:
Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Book1.xlsx;Extended Properties="Excel 12.0;HDR=YES
You may have to download the ACE provider from Microsoft in order to create XLSX files. You can find it here.
I usually use the XLS provider, so I haven't worked with the XLSX provider as much.
Hope this helps. Let me know if you have other questions.

I wrote the following code for the company some time back. It takes Enumerable of any class type and exports all its (get)properties to Excel and also open Excel. You should be able to do something similar for a DataTable. Remember you need to add reference to Microsoft.Office.Interop.Excel
public static void ExportToExcel<T>(IEnumerable<T> exportData)
{
Excel.ApplicationClass excel = new Excel.ApplicationClass();
Excel.Workbook workbook = excel.Application.Workbooks.Add(true);
PropertyInfo[] pInfos = typeof(T).GetProperties();
if (pInfos != null && pInfos.Count() > 0)
{
int iCol = 0;
int iRow = 0;
foreach (PropertyInfo eachPInfo in pInfos.Where(W => W.CanRead == true))
{
// Add column headings...
iCol++;
excel.Cells[1, iCol] = eachPInfo.Name;
}
foreach (T item in exportData)
{
iRow++;
// add each row's cell data...
iCol = 0;
foreach (PropertyInfo eachPInfo in pInfos.Where(W => W.CanRead == true))
{
iCol++;
excel.Cells[iRow + 1, iCol] = eachPInfo.GetValue(item, null);
}
}
// Global missing reference for objects we are not defining...
object missing = System.Reflection.Missing.Value;
// If wanting to Save the workbook...
string filePath = System.IO.Path.GetTempPath() + DateTime.Now.Ticks.ToString() + ".xlsm";
workbook.SaveAs(filePath, Excel.XlFileFormat.xlOpenXMLWorkbookMacroEnabled, missing, missing, false, false, Excel.XlSaveAsAccessMode.xlNoChange, missing, missing, missing, missing, missing);
// If wanting to make Excel visible and activate the worksheet...
excel.Visible = true;
Excel.Worksheet worksheet = (Excel.Worksheet)excel.ActiveSheet;
excel.Rows.EntireRow.AutoFit();
excel.Columns.EntireColumn.AutoFit();
((Excel._Worksheet)worksheet).Activate();
}
}

I have an DataTable I need to put into Excel 2007 format and save it
as an excel file(.xlsx) 2007.
Can anyone help me to achieve this?
You just need to add my free C# class to your project, and one line of code.
Full details (with free downloadable source code, and an example project) here:
Mikes Knowledge Base - Export to Excel
My library uses the free Microsoft OpenXML libraries (also provided in my downloads) to write the file, so you don't have to use the heavyweight VSTO libraries, or have Excel installed on your server.
Also, it creates a real .xlsx file, rather than some other methods which write a stream of data to a comma-separated text file, but name it as a .xls file.
By the way, I had loads of difficulties writing to Excel files using OLEDB, not least because I was running Windows 7 64-bit, with Office 2007 (which is 32-bit) and the Microsoft ACE provider has to be the 64-bit edition... but you can't install this, if you have the 32-bit version of Office installed.
So, you have to uninstall Office, install the ACE driver, and then re-install Office.
But even then, I gave up using OLEDB.. it just wasn't stable enough.

Found this in some old code I did like 5 years ago that should work...
public static void DataTableToExcel(DataTable tbl)
{
HttpContext context = HttpContext.Current;
context.Response.Clear();
foreach (DataColumn c in tbl.Columns)
{
context.Response.Write(c.ColumnName + ";");
}
context.Response.Write(Environment.NewLine);
foreach (DataRow r in tbl.Rows)
{
for (int i = 0; i < tbl.Columns.Count; i++)
{
context.Response.Write(r[i].ToString().Replace(";", string.Empty) + ";");
}
context.Response.Write(Environment.NewLine);
}
context.Response.ContentType = "text/csv";
context.Response.AppendHeader("Content-Disposition",
"attachment; filename=export.csv");
context.Response.End();
}
This will output from ASP.NET a response with a CSV file that Excel 2007 can open. If you want you can change the extension to mimic excel and it should work just by replacing the following lines:
context.Response.ContentType = "application/vnd.ms-excel";
context.Response.AppendHeader("Content-Disposition",
"attachment; filename=export.xlsx");
A CSV is the easiest way if you don't need to do anything complex. If you do require it to truly be a Excel 2007 file in the native format, you will need to use an Office library to build it or convert it from the CSV and then serve/save it.
This link might also be useful:
How to avoid the Excel prompt window when exporting data to Excel 2007

Saw that someone else posted a "save to csv" option. While that didn't seem to be the answer the OP was looking for, here is my version that includes the table's headers
public static String ToCsv(DataTable dt, bool addHeaders)
{
var sb = new StringBuilder();
//Add Header Header
if (addHeaders)
{
for (var x = 0; x < dt.Columns.Count; x++)
{
if (x != 0) sb.Append(",");
sb.Append(dt.Columns[x].ColumnName);
}
sb.AppendLine();
}
//Add Rows
foreach (DataRow row in dt.Rows)
{
for (var x = 0; x < dt.Columns.Count; x++)
{
if (x != 0) sb.Append(",");
sb.Append(row[dt.Columns[x]]);
}
sb.AppendLine();
}
return sb.ToString();
}

Related

How to read data from Excel which is open and getting updated every seconds using C# ASP.NET?

I am using Office.Interop.Excel to read data from Excel using C# ASP.Net & Dotnet 6.
I can read the Data and everything seems to be working fine.
But I have a challenge here.
The excel which I am reading data from would be updated every second.
But I am seeing an error while trying to open it and update random data.
The error says that the file is locked for editing.
Please have a look at the code below:
public double GetGoldPrice()
{
string filename = #"D:\Test.xlsx";
int row = 1;
int column = 1;
Application excelApplication = new Application();
Workbook excelWorkBook = excelApplication.Workbooks.Open(filename);
string workbookName = excelWorkBook.Name;
int worksheetcount = excelWorkBook.Worksheets.Count;
if (worksheetcount > 0)
{
Worksheet worksheet = (Worksheet)excelWorkBook.Worksheets[1];
string firstworksheetname = worksheet.Name;
var data = ((Microsoft.Office.Interop.Excel.Range) worksheet.Cells[row, column]).Value;
excelApplication.Quit();
return data;
}
else
{
Console.WriteLine("No worksheets available");
excelApplication.Quit();
return 0;
}
}
My end goal is to get live data from Excel whenever I fire the function.
The Excel would be open and can be editing any time.
Please help!
You said your file is xlsx so you would be better not using Interop but Open XML SDK 2.5. Then you can open the file in read only mode:
using (SpreadsheetDocument spreadsheetDocument =
SpreadsheetDocument.Open(fileName, false))
{
// Code removed here.
}
Check here to get familiar with Open XML SDK

Update Excel file (OpenXml format) with C#

I have a requirement to update a few columns on every row in an Excel sheet that will be uploaded from a web browser (I need to decrypt the values that are in the sheet from those columns and replace them with the true values). After the replacement happens, I will just push the updated file back down to the client.
I've worked with NPOI in the past but I'm wondering if there's a better solution out there now to accomplish this. I did a little digging before making this post and found ExcelDataReader but I couldn't find an easy way to do anything other than read Excel files using that library and my requirements are to do an update to the file.
Any suggestions would be greatly appreciated.
Here's a real simple class using the EPPlus library. It updates an Excel file by reversing the text in the first column of every row. You can test it using any Excel spreadsheet with text in the first column.
Replace ReverseText with whatever it is that decrypts the value.
public class ExcelUpdater
{
public void UpdateExcel(string pathToFile)
{
using (var package = new ExcelPackage(new FileInfo(pathToFile)))
{
var worksheet = package.Workbook.Worksheets.First();
var lastRow = worksheet.Dimension.End.Row;
for (var row = 1; row <= lastRow; row++)
{
worksheet.Cells[row, 1].Value = ReverseText(worksheet.Cells[row, 1].Text);
}
package.Save();
}
}
private string ReverseText(string value)
{
return new string(value.Reverse().ToArray());
}
}

How to fix file format and extension don't match?

I created a code in c# which creates and saves excel file. The code can successfully create and save excel file, but when I open the excel file created, it displays a warning message telling:
The file format and extension of 'filename.xls' don't match. The file could be corrupted or unsafe. Unless you trust its source, don't open it. Do you want to open it anyway?
I am using the following code:
private void button1_Click(object sender, EventArgs e)
{
saveFileDialogSummary.Filter = "Excel Flie|*.xls";
saveFileDialogSummary.FilterIndex = 0;
saveFileDialogSummary.RestoreDirectory = true;
saveFileDialogSummary.CreatePrompt = true;
saveFileDialogSummary.Title = "Export Excel File To";
Excel.Application ExcelApp = new Excel.Application();
ExcelApp.Application.Workbooks.Add(Type.Missing);
ExcelApp.Columns.ColumnWidth = 30;
for (int i = 0; i < dataGridViewSummary.Rows.Count; i++)
{
DataGridViewRow row = dataGridViewSummary.Rows[i];
for (int j = 0; j < row.Cells.Count; j++)
{
ExcelApp.Cells[i + 1, j + 1] = row.Cells[j].ToString();
}
}
DialogResult res = saveFileDialogSummary.ShowDialog();
if(res == DialogResult.OK){
ExcelApp.ActiveWorkbook.SaveCopyAs(saveFileDialogSummary.FileName);
ExcelApp.ActiveWorkbook.Saved = true;
ExcelApp.Quit();
}
}
What should I do to avoid receiving that warning message?
I know this problem may be resolved by now, but just trying to help you without modifying the code can still use .xls format in your's and suppress this warning while opening the file by setting a registry.
Open reg edit, navigate to HKEY_CURRENT_USER\Software\Microsoft\Office\14\Excel\Security
Create a DWord with name ExtensionHardening and set the value to 0.
This might get your system vulnerable, but it is not a big deal when working in organisation network, at-least when you're sure of downloading the type of doc and source.
Just change the .xls to .xlsx if you have the latest office installed.
The file extension .xls and .xlsx file contain different-different layout. the extension .xls use in version 2003 whereas then version .xlsx extension to be used.
You must export excel file to .xlsx format. It will support in all version as i used.
Add below DLLS into bin folder
1. ClosedXML.dll
2. DocumentFormat.OpenXml.dll
Code to Export to .xlsx
DataTable dt = new DataTable();
//Create column and inser rows
using (XLWorkbook wb = new XLWorkbook())
{
var ws = wb.Worksheets.Add(dt, Sheetname);
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.Charset = "";
HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + p_FileName + ".xlsx");
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(HttpContext.Current.Response.OutputStream);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
}
}
The solution for "file format and extension don't match" is to close the work book**($workbook->close;)** at last after all necessary writings done on to the file.
I faced the same issue while opening the "XLS" file from mail. I created a file and inserted all my stuff init and without closing the workbook I send the mail as an attachment. Later I realized that have to close the workbook and send as an attachment.

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.

How to import datas to excel sheet

I have datatable . I need to import those datatable values to Excel Template.How to achieve this
There are a number of options
Write the data out as an CSV file
Write the data out as an HTML table
Use Automation to manipulate a running Excel instance
Use OleDB Driver to create a Excel file. Another link from Microsoft.
Use a library like NPOI to write out an Excel file
Use a library like ExcelPackage to write out an Excel file
Use Office Open XML
Of the options, I like option 5 for performance and simplicity, especially when this is needed on the server side, option 6 is good if you require XLSX files rather than XLS, option 7 has a steep learning curve in comparison to 5 and 6.
Try this one -
// TO USE:
// 1) include COM reference to Microsoft Excel Object library
// add namespace...
// 2) using Excel = Microsoft.Office.Interop.Excel;
private static void Excel_FromDataTable(DataTable dt)
{
// Create an Excel object and add workbook...
Excel.ApplicationClass excel = new Excel.ApplicationClass();
// true for object template???
Excel.Workbook workbook = excel.Application.Workbooks.Add(true);
// Add column headings...
int iCol = 0;
foreach (DataColumn c in dt.Columns)
{
iCol++;
excel.Cells[1, iCol] = c.ColumnName;
}
// for each row of data...
int iRow = 0;
foreach (DataRow r in dt.Rows)
{
iRow++;
// add each row's cell data...
iCol = 0;
foreach (DataColumn c in dt.Columns)
{
iCol++;
excel.Cells[iRow + 1, iCol] = r[c.ColumnName];
}
}
// Global missing reference for objects we are not defining...
object missing = System.Reflection.Missing.Value;
// If wanting to Save the workbook...
workbook.SaveAs("MyExcelWorkBook.xls",
Excel.XlFileFormat.xlXMLSpreadsheet, missing, missing,
false, false, Excel.XlSaveAsAccessMode.xlNoChange,
missing, missing, missing, missing, missing);
// If wanting to make Excel visible and activate the worksheet...
excel.Visible = true;
Excel.Worksheet worksheet = (Excel.Worksheet)excel.ActiveSheet;
((Excel._Worksheet)worksheet).Activate();
// If wanting excel to shutdown...
((Excel._Application)excel).Quit();
}

Categories