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();
}
Related
I am trying to get a form that was created in visual studio WPF C# to submit to a new excel workbook will save onto a shared network drive. I have done a bit of digging trying to find the best solution and I have came across NPOI but all of the solutions seem pretty complicated compared to what I need to do. Is there some easy resource that I can reference to simply create a workbook and insert data into specific cells -- then save?
The two related packages I have seen in NuGet are DotNetCore.NPOI and NPOI which is the one I should be using?
What I have tried so far is:
private void Button_Click(object sender, RoutedEventArgs e)
{
using (var fs = new FileStream("Result12345.xlsx", FileMode.Create, FileAccess.Write))
{
IWorkbook workbook = new XSSFWorkbook();
ISheet excelSheet = workbook.CreateSheet("Sheet1");
workbook.Write(fs);
MessageBox.Show("Form submitted successfully");
}
}
This gets outputted to : Project Folder \bin\Debug\net6.0-windows and it seems to create the workbook and save (assuming all I need to do is put in the path of the network drive in the file stream then that should be easy) but how do i insert data into cells specific cells?
I have worked with Microsoft Excel via interop COM libraries and should be directly available within your WPF app by adding as reference.
First, in the solution explorer, open the references, right-click and add reference.
Then, pick the Office libraries you are interested in working with, now or future, such as other apps too.
At the top of whatever code, you will then add the "using" clauses
using Microsoft.Office.Interop.Excel;
using System;
And here is a sample code snippet so you have control of whatever active workbook, worksheet, looping through explicit rows/columns and also getting the text of a given cell.
public void tryingExcel()
{
var SomeSampleFile = #"C:\Users\Public\SomeExcelFile.xlsx";
//Start Excel and get Application object.
var XL = new Microsoft.Office.Interop.Excel.Application();
XL.DisplayAlerts = false;
XL.Workbooks.Add();
// _Workbook and _Worksheet are part of Microsoft.Office.Interop.Excel
// via "using" clause at top of code
_Workbook wb = XL.ActiveWorkbook;
wb.Sheets.Add();
_Worksheet ws = wb.ActiveSheet;
ws.Cells[2, 1] = "Date/Time:";
ws.Cells[2, 2] = DateTime.Now;
for (var ir = 4; ir < 10; ir++)
ws.Cells[ir, 2] = "testing " + ir;;
for (var ir = 4; ir < 10; ir++)
ws.Cells[ir, 4] = ws.Cells[ir, 2].Text.Trim();
XL.ActiveWorkbook.SaveAs(SomeSampleFile, XlFileFormat.xlOpenXMLWorkbook,
Type.Missing, Type.Missing, false, false,
XlSaveAsAccessMode.xlNoChange,
XlSaveConflictResolution.xlLocalSessionChanges,
Type.Missing, Type.Missing, Type.Missing, false);
XL.Quit();
}
I have figured it out like this:
private void Button_Click(object sender, RoutedEventArgs e)
{
using (var fs = new FileStream(#"\\ipaddress\sharename\Result12345.xlsx", FileMode.Create, FileAccess.Write))
{
IWorkbook workbook = new XSSFWorkbook();
ISheet excelSheet = workbook.CreateSheet("Sheet1");
//define cell to insert into
var cellTest = excelSheet.CreateRow(0).CreateCell(0);
//set cell value
cellTest.SetCellValue("Hello?");
//save the excel sheet
workbook.Write(fs);
MessageBox.Show("Form submitted successfully");
}
}
I guess I just didn't understand why I have to create a row / cell when they already exist. Rather than setting something like Cell(0,1).value = "Something"
I'm currently trying to copy a worksheet from a different workbook which i succeed by using Copy() and PasteSpecial(). However, I would like to know why the following code does not work even though many solutions online seems to use this approach.
Workbook currBook = Globals.ThisAddIn.GetActiveWorkbook();
Workbook copyBook = Globals.ThisAddIn.OpenWorkbook(Globals.ThisAddIn.Application.ActiveWorkbook.Path + #"\copyFile.xlsm", true, true);
//required worksheet
Worksheet copySheet = Globals.ThisAddIn.GetWorksheet(copyBook, "ToCopy");
copySheet.Copy(currBook.Worksheets[1]);
//close workbook
copyBook.Close();
Function used to get specific sheet:
public Excel.Worksheet GetWorksheet(Excel.Workbook book, string sheetName, bool create = false)
{
foreach (Excel.Worksheet sheet in book.Worksheets)
{
//worksheet with name found
if (sheet.Name == sheetName)
{
sheet.Activate();
return sheet;
}
}
//worksheet can't be found
if (create)
{
Excel.Worksheet sheet = book.Worksheets.Add();
sheet.Name = sheetName;
sheet.Activate();
return sheet;
}
return null;
}
There is no error from the stated code and the worksheet has been tested to exist. The program simply does not create a copy into currBook
Interestingly, I was just working on something else where this came up...
In order to specify a destination it's necessary to use Range.Copy, not Sheet.Copy:
copySheet.UsedRange.Copy(currBook.Worksheets[1].Range["A1"]);
If a destination can't be specified, then Excel puts the data in a new workbook.
I am using oledb to read .xls files in my application. It is working fine but real issue comes when my excel contains merged cells in rows or in column.
This is the data in excel
This is how it show on screen using webgrid
The VERY first thing that I would say is STAY VERY FAR AWAY FROM MERGED CELLS IN EXCEL!! That is the work of the DEVIL. Ok, if you still want to do this, consider the following options (you don't have many options) . . .
using Spire.Xls;
namespace Detect_Merged_Cells
{
class Program
{
static void Main(string[] args)
{
Workbook workbook = new Workbook();
workbook.LoadFromFile("Sample.xlsx");
Worksheet sheet = workbook.Worksheets[0];
CellRange[] range = sheet.MergedCells;
foreach (CellRange cell in range)
{
cell.UnMerge();
}
workbook.SaveToFile("Output.xlsx",ExcelVersion.Version2010);
}
}
}
OR
Excel.Range firstCell = excelWorksheet.get_Range("A1", Type.Missing);
Excel.Range lastCell = excelWorksheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing);
object[,] cellValues;
object[,] cellFormulas;
Excel.Range worksheetCells = excelWorksheet.get_Range(firstCell, lastCell);
cellValues = worksheetCells.Value2 as object[,];
cellFormulas = worksheetCells.Formula as object[,];
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.
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();
}