Export Datatable into Excel Strat from Specific Column C# - c#

I have a datatable and I want export the data into excel but start exporting from a specific column. Scenario, I have an excel sheet and first 5 columns [A-E] have data and want to export from datatable and should start from column F.
How to achieve this in C# console application?

So, the most obvious approach here would be to iterate over the data table's rows and write each to the Excel sheet manually:
Microsoft.Office.Interop.Excel.Application oXL;
Microsoft.Office.Interop.Excel._Workbook oWB;
Microsoft.Office.Interop.Excel._Worksheet oSheet;
// Start Excel and get Application object.
oXL = new Microsoft.Office.Interop.Excel.Application();
oXL.Visible = true;
// Get a new workbook.
oWB = (Microsoft.Office.Interop.Excel._Workbook)(oXL.Workbooks.Add(""));
oSheet = (Microsoft.Office.Interop.Excel._Worksheet)oWB.ActiveSheet;
// Write the data. Remember that Excel is 1-indexed
int rowIndex = 1;
foreach (DataRow row in table.Rows) {
int colIndex = 6;
foreach (DataColumn col in table.Columns) {
oSheet.Cells[rowIndex, colIndex] = row[col];
colIndex++;
}
rowIndex++;
}
// Save the Excel file
oXL.Visible = false;
oXL.UserControl = false;
oWB.SaveAs("c:\\test\\test505.xls", Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing,
false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
// Exit Excel
oWB.Close();
oXL.Quit();
There's probably a more elegant solution to this problem but I think this will get the job done, at least. As a reference, my Excel code was modified from this question, so you might be able to find a better match for your specific needs there.

Alternatively, you could try using the ClosedXML library:
XLWorkbook workbook = new XLWorkbook();
DataTable table = GetYourTable();
var sheet = workbook.Worksheets.Add(table);
var firstColumn = sheet.Column(1);
firstColumn.InsertColumnsBefore(5);
This code works by creating a new Excel worksheet from the datatable, getting a pointer to the first column in the worksheet and then inserting five columns (A - E) before it.

you can use ClosedXML library. example from my code
var wb = new XLWorkbook();
var ws = wb.Worksheets.Add("My Sheet 1");
ws.Cell("A8").Value = "Print by Admin:";
ws.Cell("B8").Value = $"{GetUserById(userId).name} - {GetUserById(userId).position_name}";
ws.Range("B8:C8").Merge();
var range = ws.Cell("B12").InsertTable(data);
range.Style.Border.TopBorder = XLBorderStyleValues.Thin;
range.Style.Border.LeftBorder = XLBorderStyleValues.Thin;
range.Style.Border.RightBorder = XLBorderStyleValues.Thin;
range.Style.Border.BottomBorder = XLBorderStyleValues.Thin;
ws.Row(12).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
ws.Row(12).Style.Font.Bold = true;
MemoryStream stream = (MemoryStream)GetStream(wb);
return File(stream.ToArray(), ""application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"", "yourfilename.xlsx");
here code for Getstream:
public Stream GetStream(XLWorkbook excelWorkbook)
{
Stream fs = new MemoryStream();
excelWorkbook.SaveAs(fs);
fs.Position = 0;
return fs;
}

Related

C# Excel Interop: Replace Isn't Replacing values

I'm using Excel interop to replace all comma values in an Excel workbook, and then saving the obtained file as a csv. I'm doing this as follows:
var app = new Application();
app.DisplayAlerts = false;
var wb = app.Workbooks.Open(excelfilename);
Worksheet sheet = wb.WorkSheets[0];
sheet.Activate();
Range last = sheet.Cells.SpecialCells(XlCellType.xlCellTypeLastCell, Type.Missing);
Range range = sheet.Range["A1", last];
int lastUsedRow = last.Row;
int lastUsedColumn = last.Column;
var startcell = sheet.Cells[1, 1];
var endcell = sheet.Cells[lastUsedRow, lastUsedColumn];
var subrange = sheet.Range[startcell, endcell];
subrange.Replace(#",", #"", XlLookAt.xlPart, XlSearchOrder.xlByColumns, false, Type.Missing, false, false);
wb.SaveAs(outputfilename, Microsoft.Office.Interop.Excel.XlFileFormat.xlCSVWindows);
wb.Close(false, "", true);
However, I found that the above code doesn't actually replace all the commas in the sheet, and I still have commas in the Worksheet before I export to CSV. What am I doing wrong?

Call and export two Gridviews into two separate worksheets

I would like to export gridview1 and gridview2 into two separate worksheets that can be named in my codes as grid view 1 and grid view 2 in one Excel file. I have trouble exporting to Excel and am not sure how to call my export in the button and pass the parameters in to export two Gridviews:
public void ExportToExcel(Microsoft.Office.Interop.Excel._Application app, Microsoft.Office.Interop.Excel._Workbook workbook, GridView gridview, string SheetName, int sheetid)
{
// creating new Excelsheet in workbook
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
// see the excel sheet behind the program
app.Visible = true;
// get the reference of first sheet. By default its name is Sheet1.
// store its reference to worksheet
worksheet = workbook.Sheets["Sheet" + sheetid];
worksheet = workbook.ActiveSheet;
// changing the name of active sheet
worksheet.Name = SheetName;
// storing header part in Excel
for (int i = 1; i < gridview.Columns.Count + 1; i++)
{
worksheet.Cells[1, i] = gridview.Columns[i - 1].HeaderText;
}
// storing Each row and column value to excel sheet
for (int i = 0; i < gridview.Rows.Count - 1; i++)
{
for (int j = 0; j < gridview.Columns.Count; j++)
{
worksheet.Cells[i + 2, j + 1] = gridview.Rows[i].Cells[j].Text.ToString();
}
}
// save the application
workbook.SaveAs(#"C:\Users\testacc\Desktop\Test\output.xls", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
// Exit from the application
app.Quit();
}
Where do I place the code below?
// creating Excel Application
Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
// creating new WorkBook within Excel application
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
you will have to create those objects in
public void callingfunction() {
Microsoft.Office.Interop.Excel._Application app
= new Microsoft.Office.Interop.Excel.Application();
// creating new WorkBook within Excel application
Microsoft.Office.Interop.Excel._Workbook workbook
= app.Workbooks.Add(Type.Missing);
ExportToExcel(app, workbook, gv1, 'sheet1', 1)
ExportToExcel(app, workbook, gv2, 'sheet2', 2)
}

How do I export 2 gridviews into 2 separate sheets in one MS Excel file?

How do I export 2 gridviews (GridView1 & GridView2) into 2 separate sheets in one MS Excel file with the click of 1 button? Currently, I'm able to export only 1 gridview to an Excel sheet which the filename is the same as the sheet name. But I would like to 2 gridviews into 2 separate sheets which I would like sheet name to be define/set by myself. Thanks
public void ExportGridToExcel()
{
Response.Clear();
Response.Buffer = true;
Response.ClearContent();
Response.ClearHeaders();
Response.Charset = "";
string FileName ="Export"+DateTime.Now+".xls";
StringWriter strwritter = new StringWriter();
HtmlTextWriter htmltextwrtter = new HtmlTextWriter(strwritter);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition","attachment;filename=" + FileName);
GridView1.GridLines = GridLines.Both;
GridView1.HeaderStyle.Font.Bold = true;
GridView1.RenderControl(htmltextwrtter);
Response.Write(strwritter.ToString());
Response.End();
}
you need to modifiy your code so that you will create a worksheet in the excel file and manually copy the data from grid to excel file and create this code as a function that takes grid,sheetname and sheetid like 1 ,2 and so on as arguments and then within button click event call it twice once for grid1 and once for grid2 with different sheetnames and sheet ids 1 and 2 respectively. the code for the function is as follows.
Write these two line of code in button click event and after that call the function twice once for each grid by passing excel app and workbook also as arguments.
// creating Excel Application
Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
// creating new WorkBook within Excel application
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
public void ExportToExcel(Microsoft.Office.Interop.Excel._Application app, Microsoft.Office.Interop.Excel._Workbook workbook,GridView gridview,string SheetName,int sheetid)
{
// creating new Excelsheet in workbook
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
// see the excel sheet behind the program
app.Visible = true;
// get the reference of first sheet. By default its name is Sheet1.
// store its reference to worksheet
worksheet = workbook.Sheets["Sheet"+ sheetid];
worksheet = workbook.ActiveSheet;
// changing the name of active sheet
worksheet.Name = sheetname;
// storing header part in Excel
for(int i=1;i<gridview.Columns.Count+1;i++)
{
worksheet.Cells[1, i] = gridview.Columns[i-1].HeaderText;
}
// storing Each row and column value to excel sheet
for (int i=0; i < gridview.Rows.Count-1 ; i++)
{
for(int j=0;j<gridview.Columns.Count;j++)
{
worksheet.Cells[i + 2, j + 1] = gridview.Rows[i].Cells[j].Value.ToString();
}
}
// save the application
workbook.SaveAs("c:\\output.xls",Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive , Type.Missing, Type.Missing, Type.Missing, Type.Missing);
// Exit from the application
app.Quit();
}
//Edit my answer since there is only 1 export button:
Take a look at this question:
firstly add these namespace:
using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;
using System.IO;
So basically you should have (or go ahead and make them) 2 DataTable (to bind to 2 gridviews): dt1 and dt2
Make a dataset and add 2 datatables to it
DataSet dataset = new DataSet();
dataset.Tables.Add(dt1);
dataset.Tables.Add(dt2);
then
//Print using Ofice InterOp
Excel.Application excel = new Excel.Application();
var workbook = (Excel._Workbook)(excel.Workbooks.Add(Missing.Value));
for (var i = 0; i < dataset.Tables.Count; i++)
{
if (workbook.Sheets.Count <= i)
{
workbook.Sheets.Add(Type.Missing, Type.Missing, Type.Missing,
Type.Missing);
}
//NOTE: Excel numbering goes from 1 to n
var currentSheet = (Excel._Worksheet)workbook.Sheets[i + 1];
for (var y = 0; y < dataset.Tables[i].Rows.Count; y++)
{
for (var x = 0; x < dataset.Tables[i].Rows[y].ItemArray.Count(); x++)
{
currentSheet.Cells[y+1, x+1] = dataset.Tables[i].Rows[y].ItemArray[x];
}
}
}
string outfile = #"C:\APP_OUTPUT\EXCEL_TEST.xlsx";
workbook.SaveAs( outfile, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing);
workbook.Close();
excel.Quit();
to change worksheet name, I believe you can do:
currentSheet.Name = "your sheet name"

How to copy excel worksheets Into another excel workbook without opening the excel file in c# winforms?

In C# windows application,
I have many excel workbooks, what i want is to copy the worksheets from the excel workbook to a single workbook.
This is possible, but i have to open the excel workbooks in order to do so.
Excel.Application app = new Excel.Application();
app.Visible = true;
app.WindowState = XlWindowState.xlMinimized;
app.Workbooks.Add("");
app.Workbooks.Add(#"Path\WorkBook1.xlsx");
app.Workbooks.Add(#"Path\WorkBook2.xlsx");
for (int i = 2; i <= app.Workbooks.Count; i++)
{
int count = app.Workbooks[i].Worksheets.Count;
app.Workbooks[i].Activate();
for (int j = 1; j <= count; j++)
{
Excel._Worksheet ws = (Excel._Worksheet)app.Workbooks[i].Worksheets[j];
ws.Select(true);
ws.Cells.Select();
Excel.Range sel = (Excel.Range)app.Selection;
sel.Copy(Type.Missing);
Excel._Worksheet sheet = (Excel._Worksheet)app.Workbooks[1].Worksheets.Add(
Type.Missing, Type.Missing, Type.Missing, Type.Missing
);
sheet.Paste(Type.Missing, Type.Missing);
sheet.Name = app.Workbooks[i].Worksheets[j].Name;
}
}
app.DisplayAlerts = false;
app.Workbooks[3].Close();
app.Workbooks[2].Close();
app.DisplayAlerts = true;
Cursor = Cursors.Default;
MessageBox.Show("Successfully Generated Excel...!", "Excel Tool", MessageBoxButtons.OK, MessageBoxIcon.Information);
Is is possible without opening the excel sheets, copy all the data with their styles ?
To copy a worksheet and all its contents and formatting without selecting and copying the contents of the worksheet itself you can make use of Worksheet.Copy. You'd use it like so:
Excel._Worksheet ws = (Excel._Worksheet)app.Workbooks[i].Worksheets[j];
Excel._Worksheet sheet = (Excel._Worksheet)app.Workbooks[1].Worksheets.Add(
Type.Missing, Type.Missing, Type.Missing, Type.Missing
);
ws.Copy(Before: sheet);
If, however, what you actually mean by your question is that you want to copy the contents of the workbooks into one common workbook without ever opening the file, then I don't believe that's possible. You need to open the file to access the data.

How to merge two Excel workbook into one workbook in C#?

Let us consider that I have two Excel files (Workbooks) in local. Each Excel workbook is having 3 worksheets.
Lets say WorkBook1 is having Sheet1, Sheet2, Sheet3
Workbook2 is having Sheet1, Sheet2, Sheet3.
So here I need to merge these two excel workbook into one and the new excel workbook that is let's say Workbook3 which will have total 6 worksheets (combination of workbook1 and workbook2).
I need the code that how to perform this operation in c# without using any third party tool. If the third party tool is free version then its fine.
An easier solution is to copy the worksheets themselves, and not their cells.
This method takes any number of excel file paths and copy them into a new file:
private static void MergeWorkbooks(string destinationFilePath, params string[] sourceFilePaths)
{
var app = new Application();
app.DisplayAlerts = false; // No prompt when overriding
// Create a new workbook (index=1) and open source workbooks (index=2,3,...)
Workbook destinationWb = app.Workbooks.Add();
foreach (var sourceFilePath in sourceFilePaths)
{
app.Workbooks.Add(sourceFilePath);
}
// Copy all worksheets
Worksheet after = destinationWb.Worksheets[1];
for (int wbIndex = app.Workbooks.Count; wbIndex >= 2; wbIndex--)
{
Workbook wb = app.Workbooks[wbIndex];
for (int wsIndex = wb.Worksheets.Count; wsIndex >= 1; wsIndex--)
{
Worksheet ws = wb.Worksheets[wsIndex];
ws.Copy(After: after);
}
}
// Close source documents before saving destination. Otherwise, save will fail
for (int wbIndex = 2; wbIndex <= app.Workbooks.Count; wbIndex++)
{
Workbook wb = app.Workbooks[wbIndex];
wb.Close();
}
// Delete default worksheet
after.Delete();
// Save new workbook
destinationWb.SaveAs(destinationFilePath);
destinationWb.Close();
app.Quit();
}
Edit: notice that you might want to Move method instead of Copy in case you have dependencies between the sheets, e.g. pivot table, charts, formulas, etc. Otherwise the data source will disconnect and any changes in one sheet won't effect the other.
Here's a working sample that joins two books into a new one, hope it will give you an idea:
using System;
using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;
namespace MergeWorkBooks
{
class Program
{
static void Main(string[] args)
{
Excel.Application app = new Excel.Application();
app.Visible = true;
app.Workbooks.Add("");
app.Workbooks.Add(#"c:\MyWork\WorkBook1.xls");
app.Workbooks.Add(#"c:\MyWork\WorkBook2.xls");
for (int i = 2; i <= app.Workbooks.Count; i++)
{
int count = app.Workbooks[i].Worksheets.Count;
app.Workbooks[i].Activate();
for (int j=1; j <= count; j++)
{
Excel._Worksheet ws = (Excel._Worksheet)app.Workbooks[i].Worksheets[j];
ws.Select(Type.Missing);
ws.Cells.Select();
Excel.Range sel = (Excel.Range)app.Selection;
sel.Copy(Type.Missing);
Excel._Worksheet sheet = (Excel._Worksheet)app.Workbooks[1].Worksheets.Add(
Type.Missing, Type.Missing, Type.Missing, Type.Missing
);
sheet.Paste(Type.Missing, Type.Missing);
}
}
}
}
}
You're looking for Office Autmation libraries in C#.
Here is a sample code to help you get started.
System.Data.Odbc.OdbcDataAdapter Odbcda;
//CSV File
strConnString = "Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq=" + SourceLocation + ";Extensions=asc,csv,tab,txt;Persist Security Info=False";
sqlSelect = "select * from [" + filename + "]";
System.Data.Odbc.OdbcConnection conn = new System.Data.Odbc.OdbcConnection(strConnString.Trim());
conn.Open();
Odbcda = new System.Data.Odbc.OdbcDataAdapter(sqlSelect, conn);
Odbcda.Fill(ds, DataTable);
conn.Close();
This would read the contents of an excel file into a dataset.
Create multiple datasets like this and then do a merge.
Code taken directly from here.

Categories