how to consolidate data in excel from multiple worksheets? - c#

I have to merge the worksheet and worksheet 1 data into a single sheet. I tried the FileStream method to open the file and read the data from there and paste it into the destination worksheet.
Qdv.UserApi.IWbs WBS = es.CurrentVersion.Wbs;
System.Data.DataTable Tasks = WBS.GetFullData(true, new Qdv.UserApi.LocationOfTotals());
// Create a new workbook and worksheet.
SpreadsheetGear.IWorkbook workbook = SpreadsheetGear.Factory.GetWorkbook();
SpreadsheetGear.IWorksheet worksheet = workbook.Worksheets["Sheet1"];
// Get the top left cell for the DataTable.
SpreadsheetGear.IRange range = worksheet.Cells["A1"];
// Copy the DataTable to the worksheet range.
range.CopyFromDataTable(Tasks, SpreadsheetGear.Data.SetDataFlags.None);
//Auto size all worksheet columns which contain data.
worksheet.UsedRange.Columns.AutoFit();
worksheet.Name = "WBS Details";
SpreadsheetGear.IWorkbook WBK = es.GetActiveMinuteWorkbook(true);
SpreadsheetGear.IWorksheet worksheet1 = WBK.Worksheets[0];
worksheet1.Name = "Minutes Details";

It's a bit unclear in your question what is the source sheet and destination sheet, and where exactly you plan to copy the contents in the destination sheet. So for now I will provide a more generalized answer on how to copy one range to another. If you need more clarity for your particular case, please update your post with more code or pseudo-code that makes your intentions clear.
In general, you can use IRange.Copy(...) to copy one range to another, which can include from one sheet to another. You can use IWorksheet.UsedRange to get the portion of a worksheet that is "used" which in your case might be handy to both figure out what "source" range to copy as well as figure out where in relation to the destination sheet's used range where to copy the source range to.
For example, the below sample code takes the UsedRange from the "src" worksheet and copies it directly below the UsedRange of the "dest" worksheet:
// Get source workbook, worksheet, used range.
IWorkbook srcWorkbook = Factory.GetWorkbook("...");
IWorksheet srcWorksheet = srcWorkbook.Worksheets["Sheet1"];
IRange srcUsedRange = srcWorksheet.UsedRange;
// Get destination workbook, worksheet, used range.
IWorkbook destWorkbook = Factory.GetWorkbook("...");
IWorksheet destWorksheet = destWorkbook.Worksheets["Sheet1"];
IRange destUsedRange = destWorksheet.UsedRange;
// Get the number of rows in the destination used range.
int destUsedRangeRowCount = destUsedRange.RowCount;
// Use the IRange[...] indexer to create a new IRange that represents the cell
// immediately below "destUsedRange" and in the same first column. So if
// "destUsedRange" is A1:D15, then "destRange" would be A16.
IRange destRange = destUsedRange[destUsedRangeRowCount, 0];
// Copy source range to destination range.
srcUsedRange.Copy(destRange);

Related

Generate a spreadsheet with multiple worksheets from Microsoft C#

Existing C# code created in Visual Studio generates a complete report in the form of an Excel workbook with the report formatted in a single worksheet in that workbook. Need to create a workbook with a variable number of worksheets with the same report format but with different data values on each worksheet.
Current C# program creates a workbook with a single worksheet using the following code:
oWB = (Excel._Workbook)(oXL.Workbooks.Add(Missing.Value)); //Get a new workbook.
oSheet = (Excel._Worksheet)oWB.ActiveSheet; // add a worksheet
Tried using a "FOR" loop using the index of the FOR loop to name the worksheets. How can the worksheet reference ("oSheet") be indexed in the loop? Adding the FOR loop "ii" index to the oSheet name give a compiler error:
oWB = (Excel._Workbook)(oXL.Workbooks.Add(Missing.Value)); //Get a new workbook.
for (int ii = count; ii > 0; ii--)
{
oSheet[ii] = (Excel._Worksheet)oWB.ActiveSheet; // add a worksheet

How to merge Worksheets from Multiple Workbooks into New WorkBook

I want to merge data from multiple worksheets of multiple workbooks.
For example, I have multiple Workbooks with multiple worksheets.
So consider I want to merge data from "Worksheet1" of "WorkBook1" and data from "Worksheet2" of "Workbook2" and respectively into "NewWorkSheet" of New "WorkBook". I want to do this in a way that data is inserted into "NewWorkSheet" one below the other, like the first 20 rows from "Worksheet1" then
next 20 from "Worksheet2" and so on...
I could merge into a new one only from one worksheet only but not from others.
Workbook xlWorkbookDLA3 = xlApp.Workbooks.Open(dropBoxPath + "Week49DLA3.xlsm");
Worksheet worksheetDLA3 = xlWorkbookDLA3.Worksheets["Wed-A"];
Workbook xlWorkbookDLA4 = xlApp.Workbooks.Open(dropBoxPath + "Week49DLA4.xlsm");
Worksheet worksheetDLA4 = xlWorkbookDLA4.Worksheets["Thurs-A"];
Workbook destionationworkBook = xlApp.Workbooks.Open(dropBoxPath + "Test.xlsm");
Worksheet destworkSheet = destionationworkBook.Worksheets["Sheet2"];
Microsoft.Office.Interop.Excel.Range from, to;
from = worksheetDLA3.Range["B7:S7"].EntireColumn;
to = destworkSheet.Range["B7:S7"].EntireColumn;
from.Copy(to);
destionationworkBook.SaveAs(#"C:\Users\ashish.mokadam\Desktop\DropBox\Test" + ".xlsm");
For each subsequent worksheet you wish to copy from (note, NOT for the 1st worksheet), insert the following code sample between "from.Copy(to);" and "destionationworkBook.SaveAs(...":
var destination_start_row = destworkSheet.UsedRange.Rows.Count + 1; // + 1 because Excel is 1-indexed
var source_used_rows = worksheetDLA4.UsedRange.Rows.Count;
from = worksheetDLA4.Range["B1:S" + source_used_rows];
to = destworkSheet.Range["B" + destination_start_row + ":S" + destination_start_row + source_used_rows];
from.Copy(to);
The problem is that you are trying to copy entire columns from the source worksheets to the destination worksheet, thus overwriting the values in the destination worksheet. This code only copies a range of cells, not entire columns of data.
Also, you have a typo in your variable name "destionationworkBook". It should be "destinationworkBook".

How to merge 3 Sheets from different Excel files into one sheet with C#

Here I tried to merge two excel files into one excel sheet using below mentioned code (Spire.Xls dll) its working fine.
Here is code for two excel merging.
workbook = new Workbook();
//load the first workbook
workbook.LoadFromFile(ArrayExcelFiles[0]);
//load the second workbook
Workbook workbook2 = new Workbook();
workbook2.LoadFromFile(ArrayExcelFiles[1]);
//import the second workbook's worksheet into the first workbook using a datatable
Worksheet sheet2 = workbook2.Worksheets[0];
DataTable dataTable = sheet2.ExportDataTable();
Worksheet sheet1 = workbook.Worksheets[0];
sheet1.InsertDataTable(dataTable, false, sheet1.LastRow + 1, 1);
workbook.SaveToFile(OutputPath + "Merged.xls", ExcelVersion.Version2007);
But the problem is that when am trying to merge three excel files using same logic the output was same as two merged excel output third excel is not merged.
Here is the code for three excel files.
Workbook workbook1 = new Workbook();
//load the first workbook
workbook1.LoadFromFile(ArrayExcelFiles[0]);
//load the second workbook
Workbook workbook2 = new Workbook();
workbook2.LoadFromFile(ArrayExcelFiles[1]);
//load the third workbook
Workbook workbook3 = new Workbook();
workbook3.LoadFromFile(ArrayExcelFiles[2]);
//import the second workbook's worksheet into the first workbook using a datatable
Worksheet sheet3 = workbook3.Worksheets[0];
DataTable dataTable = sheet3.ExportDataTable();
Worksheet sheet2 = workbook2.Worksheets[0];
dataTable = sheet2.ExportDataTable();
Worksheet sheet1 = workbook1.Worksheets[0];
sheet1.InsertDataTable(dataTable, false, sheet1.LastRow + 1, 1);
workbook1.SaveToFile(OutputPath + "Merged.xls", ExcelVersion.Version2007);
You are not using the same logic in the second example, thus it does not work. Try something like this on the second code or change it a bit:
//import the second workbook's worksheet into the first workbook using a datatable
Worksheet sheet3 = workbook3.Worksheets[0];
Worksheet sheet2 = workbook2.Worksheets[0];
DataTable dataTable2 = sheet2.ExportDataTable();
Worksheet sheet1 = workbook1.Worksheets[0];
DataTable dataTable1 = sheet1.ExportDataTable();
sheet3.InsertDataTable(dataTable2, false, sheet3.LastRow + 1, 1)
sheet3.InsertDataTable(dataTable1, false, sheet3.LastRow + 1, 1)
The code above takes sheet3 and inserts 2 data tables to it - one from sheet2 and one from sheet1.
You only ever insert the sheet from workbook2, so it's not surprising. You got datatable from workbook3, but then immediately over-wrote it with data from workbook2, before you did anything else with it. You can't store two tables in one DataTable object. The last one simply replaces the first one (just like any other variable assignment).
You need to run two separate insertDataTable commands with two separate data tables, one from each sheet:
//import the second and third workbooks' worksheets into the first workbook using a datatable
Worksheet sheet2 = workbook2.Worksheets[0];
DataTable dataTable = sheet2.ExportDataTable();
Worksheet sheet3 = workbook3.Worksheets[0];
DataTable dataTable2 = sheet3.ExportDataTable();
Worksheet sheet1 = workbook1.Worksheets[0];
sheet1.InsertDataTable(dataTable, false, sheet1.LastRow + 1, 1);
sheet1.InsertDataTable(dataTable2, false, sheet1.LastRow + 1, 1);
workbook1.SaveToFile(OutputPath + "Merged.xls", ExcelVersion.Version2007);
Of course the code could be made a lot neater and less repetitive by using loops etc, but this is the basic solution.

Insert range of cells at the beginning of an existing excel worksheet?

I have a worksheet that has 5 rows and 3 columns. I make a copy of this sheet:
activeSheet.Copy(Type.Missing, activeSheet);
var outputSheetIndex = activeSheet.Index + 1;
var outputSheet = (Worksheet)application.Sheets[outputSheetIndex];
The above copies the sheet into another sheet. I now want to insert another range into the outputSheet and shift the outputSheet columns to the right.
I am not sure on which range object to apply the Insert method on.
I tried creating a new range to insert in the beginning, but this doesn't work:
var startCell = outputSheet.Cells[1, 1];
var endCell = outputSheet.Cells[output.Count(),
properties.Length + 1];
var writeRange = outputSheet.Range[startCell, endCell];
writeRange.Insert(XlInsertShiftDirection.xlShiftToRight);
When I insert writeRange, I want the existing range of data to be shifted to the right.
If all you want to do is insert a blank column on your new (copied worksheet), I think this would work:
outputSheet.Range["A:A"].Insert(
Microsoft.Office.Interop.Excel.XlInsertShiftDirection.xlShiftToRight,
Type.Missing);
If you want the column somewhere else, you would change "A:A" to your desired range.

Aspose workbook copy/rename sheet

I want to Copy Sheet from excel, create copy of sheet with particular name.
Aspose.Cells.Workbook workbook = new Aspose.Cells.Workbook(excelFilePath);
//Create a Worksheets object with reference to the sheets of the Workbook.
WorksheetCollection sheets = workbook.Worksheets;
sheets.AddCopy("Cash Bonuses");
Now the problem is it copies data of Sheet "Cash Bonuses" but it makes Sheet name as "Sheet111". I want to make this sheet with specified name like "Cash".How to do that ? Once data is copied to new tab , i want to delete old tab "Cash Bonuses" and rename new tab as "Cash bonuses" from "Cash".
Please note, in order to copy the contents of a worksheet to another worksheet, you need to add a blank worksheet to the collection and then call its Copy method while passing the object of existing worksheet (one that needs to be copied) otherwise you will lose data on the destination worksheet.
Please try the following piece of code as it tries to accomplish all your requirements. Hopefully, the comments will help you understand what the statements mean.
var workbook = new Aspose.Cells.Workbook(excelFilePath);
var sheets = workbook.Worksheets;
//Access 1st worksheet from the collection
//You may also pass the worksheet name to access a particular worksheet
var sheet0 = sheets[0];
//Add a new worksheet to the collection and name it as desired
var sheet1 = sheets[sheets.Add()];
sheet1.Name = "Cash";
//Copy the contents of 1st worksheet onto the new worksheet
sheet1.Copy(sheet0);
//Delete 1st worksheet
sheets.RemoveAt(sheet0.Index);
//Rename newly added worksheet to 'Cash bonuses'
sheet1.Name = "Cash bonuses";
//Save result
workbook.Save(dir + "output.xlsx");
Note: I work with Aspose as Developer Evangelist.

Categories