Merge Individual excel sheets data to Single Excel with multiple sheet - c#

I am facing an issue regarding excel writing .Below is the problem -
I have a requirement for which I have multiple excel sheets and for each excel file there could be multiple sheets .So, I need to write in a single excel with multiple individual sheets
ex- Lets say I have 3 excel file File1.xlsx with Sheet1, File2.xlsx with Sheet2 and File 3 with multiple sheet Sheet3 and Sheet4.In each sheet the data is similar like 3 Columns (Name,EmployeeID,MobNo) So, the output would be Individual file Result.xlsx with multiple sheets Sheet1,Sheet2,Sheet3 & Sheet4.
Please share the code without any third party tools like Spire.xl.I need to do this programatically.Below is the code -
string inputPathFirstExcel =
#"C:\MyData\ExcelWritingApp\File1.xlsx";
string inputPathSecondExcel = #"C:\\ExcelWritingApp\File2.xlsx";
string[] ColumnData = { };
Excel.Application xlApp = null;
Excel.Workbook xlWorkBook = null;
Excel.Worksheet xlWorkSheet = null;
Excel.Range xlrange = null;
xlApp = new Excel.Application();
xlApp.Visible = false;
xlWorkBook = xlApp.Workbooks.Open(inputPathFirstExcel);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Sheets[1];
xlrange = xlWorkSheet.UsedRange;
object missing = Type.Missing;
Excel.Application oXL = new Excel.Application();
oXL.Visible = false;
Excel.Workbook oWB = oXL.Workbooks.Add(missing);
Excel.Worksheet oSheet = oWB.ActiveSheet as Excel.Worksheet;
oSheet.Name = "Sheet1";
Microsoft.Office.Interop.Excel.Range xlRange = xlWorkSheet.UsedRange;
DataTable dt = new DataTable();
dt.Columns.Add("Name");
dt.Columns.Add("Employee");
dt.Columns.Add("MobNo");
int rowCount = xlRange.Rows.Count;
int colCount = xlRange.Columns.Count;
for (int i = 1; i <= colCount; i++)
{
oSheet.Cells[1, i] = dt.Columns[i - 1].ToString().ToUpper() + "\t";
}
for (int i = 0; i < rowCount; i++)
{
for (int j = 1; j <= colCount; j++)
{
oSheet.Cells[i + 2, j] = Convert.ToString((xlRange.Cells[i + 2, j] as Excel.Range).Value2);
}
}
string fileName = #"C:\Result.xlsx";
oWB.SaveAs(fileName, Excel.XlFileFormat.xlOpenXMLWorkbook,
missing, missing, missing, missing,
Excel.XlSaveAsAccessMode.xlNoChange,
missing, missing, missing, missing, missing);

Related

interop error HRESULT: 0x80020005 (DISP_E_TYPEMISMATCH) on server

I am having a problem with my app when trying to run on the server.
In my place it works fine but when passed to the server it fails to try to create the pivotcache.
Excel has permissions on the server with the user IIS, on my computer I have Office 365 and Office 2010 on server.
please help.error
Excel.Application oApp;
Excel.Worksheet oSheet;
Excel.Workbook oBook;
//Create COM Objects. Create a COM object for everything that is referenced
oApp = new Excel.Application();
oBook = oApp.Workbooks.Open(fileTest);
oSheet = oBook.Sheets[1];
//Range = oSheet.Range["A9","BN36"];
//Excel.Worksheet oSheet2 = oBook.Worksheets.Add();
//oSheet2.Name = "Pivot Table";
//oApp = new Excel.Application();
//oBook = oApp.Workbooks.Add();
//oSheet = (Excel.Worksheet)oBook.Worksheets.get_Item(1);
//oSheet.Cells[1, 1] = "Name";
//oSheet.Cells[1, 2] = "Salary";
//oSheet.Cells[2, 1] = "Frank";
//oSheet.Cells[2, 2] = 150000;
//oSheet.Cells[3, 1] = "Ann";
//oSheet.Cells[3, 2] = 300000;
Excel.Range last = oSheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing);
Excel.Range range = oSheet.get_Range("A1", last);
int lastUsedRow = last.Row;
int lastUsedColumn = last.Column;
//// now capture range of the first sheet = I will need this to create pivot table
Excel.Range oRange = oSheet.Range["A1", "AJ708"];
// create second sheet
if (oApp.Application.Sheets.Count < 2)
{
oSheet = (Excel.Worksheet)oBook.Worksheets.Add();
}
else
{
oSheet = oApp.Worksheets[2];
}
oSheet.Name = "Resumen";
// specify first cell for pivot table
Excel.Range oRange2 = oSheet.Cells[1, 1];
// create Pivot Cache and Pivot Table heres trow exception error
Excel.PivotCache oPivotCache = (Excel.PivotCache)oBook.PivotCaches().Add(Excel.XlPivotTableSourceType.xlDatabase, oRange);
Excel.PivotTable oPivotTable = (Excel.PivotTable)oSheet.PivotTables().Add(PivotCache: oPivotCache, TableDestination: oRange2, TableName: "Summary");
solved.
trying change this line
var oPivotCache = pivotCaches.Create(Excel.XlPivotTableSourceType.xlDatabase, "Sheet1!$A$1:$AL$" + lastUsedRow);
the correct format to pass a range on office 2010 i think so.

Convert excel workbook to memory stream/byte array to download

I've created an excel workbook. Can I convert this excel workbook directly to memory stream or byte array to pass it through HTTP? I don't want to save the excel workbook. I need to download this excel file via angular js. I'm using Web API 2
using Excel = Microsoft.Office.Interop.Excel;
private MemoryStream ExportDataSetToExcel()
{
System.Data.DataTable employeeTable = new System.Data.DataTable("Employee");
employeeTable.Columns.Add("Employee ID");
employeeTable.Columns.Add("Employee Name");
employeeTable.Rows.Add("1", "ABC");
employeeTable.Rows.Add("2", "DEF");
employeeTable.Rows.Add("3", "PQR");
employeeTable.Rows.Add("4", "XYZ");
////Create a Department Table
System.Data.DataTable departmentTable = new System.Data.DataTable("Department");
departmentTable.Columns.Add("Department ID");
departmentTable.Columns.Add("Department Name");
departmentTable.Rows.Add("1", "IT");
departmentTable.Rows.Add("2", "HR");
departmentTable.Rows.Add("3", "Finance");
////Create a DataSet with the existing DataTables
DataSet ds = new DataSet("Organization");
ds.Tables.Add(employeeTable);
ds.Tables.Add(departmentTable);
////Creae an Excel application instance
Excel.Application excelApp = new Excel.Application();
excelApp.Visible = true;
Excel.Workbook excelWorkBook = excelApp.Workbooks.Add();
foreach (System.Data.DataTable table in ds.Tables)
{
////Add a new worksheet to workbook with the Datatable name
Microsoft.Office.Interop.Excel.Worksheet excelWorkSheet = excelWorkBook.Sheets.Add();
excelWorkSheet.Name = table.TableName;
for (int i = 1; i < table.Columns.Count + 1; i++)
{
excelWorkSheet.Cells[1, i] = table.Columns[i - 1].ColumnName;
excelWorkSheet.Cells[1, i].Font.Bold = true;
}
for (int j = 0; j < table.Rows.Count; j++)
{
for (int k = 0; k < table.Columns.Count; k++)
{
excelWorkSheet.Cells[j + 2, k + 1] = table.Rows[j].ItemArray[k].ToString();
excelWorkSheet.Cells[j + 2, k + 1].Interior.Color = Excel.XlRgbColor.rgbRed;
}
}
}
MemoryStream ms = new MemoryStream();
////excelWorkBook.SaveAs(ms, Type.Missing, Type.Missing, Type.Missing, true, false, Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing);
excelWorkBook.Close();
excelApp.Quit();
return ms;
}
You can not convert directly. You must save your file to a temporary path
public byte[] GetActiveWorkbook(Microsoft.Office.Interop.Excel.Application app)
{
string path = Path.GetTempFileName();
try
{
app.ActiveWorkbook.SaveCopyAs(path);
return File.ReadAllBytes(path);
}
finally
{
if(File.Exists(path))
File.Delete(path);
}
}

how to create excel sheet which contain maximum 30 sheets in c#

I want to create excel from datatable, And want to create maximum 25 sheets(each day for current month excluding weekend, Saturday,Sunday and bank holiday) , how can we do this by taking string of array for total days in month and datatable.
Public static void CreateExcel_TabNameUnique( DataTable dt1,string ExcelFilePath, string Tab_Name1)
{
try
{
runDate = DateTime.Today;
currMonth = DateTime.Today;
object missing = Type.Missing;
Excel.Application oXL = new Excel.Application();
oXL.Visible = false;
Excel.Workbook oWB = oXL.Workbooks.Add(missing);
Excel.Worksheet oSheet = oWB.ActiveSheet as Excel.Worksheet;
oSheet.Name = Tab_Name1;
// column headings
for (int i = 0; i < dt1.Columns.Count; i++)
{
oSheet.Cells[1, (i + 1)] = dt1.Columns[i].ColumnName;
}
// rows
for (int i = 0; i < dt1.Rows.Count; i++)
{
for (int j = 0; j < dt1.Columns.Count; j++)
{
oSheet.Cells[(i + 2), (j + 1)] = dt1.Rows[i][j];
}
}
if (ExcelFilePath != null && ExcelFilePath != "")
{
try
{
oWB.SaveAs(ExcelFilePath, Excel.XlFileFormat.xlOpenXMLWorkbook,
missing, missing, missing, missing,
Excel.XlSaveAsAccessMode.xlNoChange,
missing, missing, missing, missing, missing);
oWB.Close(missing, missing, missing);
oXL.UserControl = true;
oXL.Quit();
}
catch (Exception ex)
{
}
}
}
catch (Exception ex)
{
}
}
Sorry for not being able to verify this at the moment (problems with Excel Interop...), but from your comment I take it your problem is just in adding a second worksheet. You should be able to do this with:
Excel.Worksheet secondWorkSheet = oWB.Worksheets.Add();
Then proceed to manipulate worksheet as you are doing in the code you posted.

Insert 2D array into excel in C# WPF

I want to insert String[][] (2D array) to excel instead of "cell by cell" or by Row.
Another thing:
I want to open a template XLS file, write into it and save it with a different name.
I tried to search google for 2 days already.
Please help me :-)
(in C# WPF)
what i finally did is using object[,], and insert ro by row
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Open(ExcelFile);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
Excel.Range firstCell = xlWorkSheet.get_Range("A1", Type.Missing);
Excel.Range lastCell = xlWorkSheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing);
Excel.Range worksheetCells = xlWorkSheet.get_Range(firstCell, lastCell);
int rowCount = worksheetCells.Rows.Count;
int colCount = worksheetCells.Columns.Count;
object[,] cellFormulas = new String[rowCount, colCount];
cellFormulas = worksheetCells.Formula as object[,];
// String[][] ResultMatrix = new String[rowCount][];
xlWorkBook.Close(true, misValue, misValue);
xlApp.Workbooks.Close();'
You want something like:
Although I think it will only work on jagged arrays and not 2d arrays. Not tested on 2d arrays.
var startCell = Worksheet.Cells[row, col];
var endCell = Worksheet.Cells[row, col];
var writeRange = (Excel.Range)Worksheet.Cells[startCell, endCell];
writeRange.Value = myArray;
I can solve the first problem which is:
I want to insert String [] [] (2D array) to excel instead "cell by cell" or by Row.
In first you should convert String[][] to String[,] and then use this (I tested it):
public static void ExportToExcel(String[,] data, String sheetName, String path)
{
var dt = new DataTable();
for (var row = 0; row < data.GetLength(0); ++row)
{
for (var col = 0; col < data.GetLength(1); col++)
{
dt.Rows[row][col] = data[row, col];
}
}
Excel.Application oXL;
Excel.Workbook oWB;
Excel.Worksheet oSheet;
//Excel.Range oRange;
oXL = new Excel.Application();
oXL.Visible = true;
oXL.DisplayAlerts = false;
oWB = oXL.Workbooks.Add(Missing.Value);
oSheet = (Excel.Worksheet)oWB.ActiveSheet;
oSheet.Name = sheetName;
var rowCount = 1;
foreach (DataRow dr in dt.Rows)
{
rowCount += 1;
for (var i = 1; i < dt.Columns.Count + 1; i++)
{
if (rowCount == 2)
{
oSheet.Cells[1, i] = dt.Columns[i - 1].ColumnName;
}
oSheet.Cells[rowCount, i] = dr[i - 1].ToString();
}
}
oSheet = null;
oWB.SaveAs(path, Excel.XlFileFormat.xlWorkbookNormal,
Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Excel.XlSaveAsAccessMode.xlExclusive,
Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value);
oWB.Close(Missing.Value, Missing.Value, Missing.Value);
oWB = null;
oXL.Quit();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
Note: use should add Microsoft.Office.Interop.Excel in your references.

How to generate line chart from datatable c# winform

i am using Interop.Excel to export data from datatable and generate line chart too.
i could successfully export data to excel from data like this way
public static bool Export(System.Data.DataTable dt, string sheetName)
{
object Missing = System.Reflection.Missing.Value;
Excel.Application oXL;
Excel.Workbook oWB;
Excel.Worksheet oSheet;
Excel.Range oRange;
try
{
// Start Excel and get Application object.
oXL = new Excel.Application();
// Set some properties
oXL.Visible = false;
oXL.DisplayAlerts = false;
// Get a new workbook.
oWB = oXL.Workbooks.Add(Missing);
// Get the Active sheet
oSheet = (Excel.Worksheet)oWB.ActiveSheet;
oSheet.Name = sheetName;
oSheet.Cells[1, 1] = "Daily Finished Job History " + DateTime.Now.ToString("dd/MM/yyyy");
oSheet.get_Range("A1", "A1").ColumnWidth = 13;
oSheet.get_Range("B1", "B1").ColumnWidth = 13;
oSheet.get_Range("C1", "C1").ColumnWidth = 25;
oSheet.get_Range("A1", "C1").Font.Size = 14;
oSheet.get_Range("A1", "C1").Font.Bold = true;
oSheet.get_Range("A1", "C1").Merge(true);
oSheet.get_Range("A1", "C1").Cells.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
oSheet.get_Range("A3", "C3").Font.Bold = true;
int rowCount = 3;
for (int i = 1; i < dt.Columns.Count + 1; i++)
{
oSheet.Cells[rowCount, i] = dt.Columns[i - 1].ColumnName;
}
foreach (DataRow dr in dt.Rows)
{
rowCount += 1;
for (int i = 1; i < dt.Columns.Count + 1; i++)
{
oSheet.Cells[rowCount, i] = dr[i - 1].ToString();
}
}
// Resize the columns
oRange = oSheet.get_Range(oSheet.Cells[1, 1],
oSheet.Cells[rowCount, dt.Columns.Count]);
//oRange.EntireColumn.AutoFit();
// Save the sheet and close
oSheet = null;
oRange = null;
string strParentDirectory = GetParentDirectory();
strParentDirectory = strParentDirectory + "\\Data";
if (!Directory.Exists(strParentDirectory))
{
Directory.CreateDirectory(strParentDirectory);
}
string strFileName = strParentDirectory + "\\DailyFinishedJobHistory_" + DateTime.Now.ToString("yyyyMMdd") + ".xls";
if (File.Exists(strFileName))
{
File.Delete(strFileName);
}
FileStream file = new FileStream(strFileName, FileMode.Create);
file.Close();
oWB.SaveAs(strFileName, Excel.XlFileFormat.xlWorkbookNormal,
Missing, Missing, Missing, Missing,
Excel.XlSaveAsAccessMode.xlExclusive,
Missing, Missing, Missing,
Missing, Missing);
oWB.Close(Missing, Missing, Missing);
oWB = null;
oXL.Quit();
}
catch
{
throw;
}
finally
{
// Clean up
// NOTE: When in release mode, this does the trick
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
return true;
}
public static string GetParentDirectory()
{
System.IO.DirectoryInfo myDirectory = new DirectoryInfo(Environment.CurrentDirectory);
return myDirectory.Parent.Parent.FullName;
}
now i want to generate chart in same sheet based on data from my datatable.
my excel file would look like as follows
i read few article & code to generate chart from this links
http://www.dotnetbull.com/2011/09/exporting-pie-chart-into-excel-file.html
http://csharp.net-informations.com/excel/csharp-excel-chart.htm
http://www.daniweb.com/software-development/csharp/threads/80834/c-and-excel-chart-ranges
but still not being able to understand the code to generate line chart. it would be great help if some help me to generate chart in same sheet like the image i have given here.
thanks
Try this as a starting point:
'Create & Format Chart
Dim oChart As Excel.Chart
oChart = oXL.Parent.Charts.Add
With oChart
.Name = "History"
.HasTitle = True
.ChartTitle.Font.ColorIndex = 11
.ChartTitle.Font.Bold = True
.ChartTitle.Font.Size = 12
.ChartTitle.Font.Name = "Arial"
.ChartTitle.Text = "Job History"
.ChartType = Excel.XlChartType.xlLine
.HasLegend = True
.SeriesCollection(1).XValues = "=Sheet1!$A$4:$A$6"
.SeriesCollection(1).Name = "=Sheet1!$B$3"
.SeriesCollection(2).Name = "=Sheet1!$C$3"
.SeriesCollection(3).Name = "=Sheet1!$D$3"
End With

Categories