I have a Word.Chart whose underlying worksheet I am populating with data from C#.
My problem is however, that the selected dataset in the worksheet contains just the default selection (eg. 5x4 cells or sg like that), and not ALL the data which I entered.
If the object were an Excel chart, I could do
Excel.Range rangeBegin = ws.Cells[1, 1];
Excel.Range rangeEnd = ws.Cells[xAxisContents.Count + 1, feeds.Count + 1];
Excel.Range chartRange = ws.get_Range(rangeBegin, rangeEnd);
wordChart.SetSourceData(chartRange);
However, the Word.Chart's SetSourceData method only accepts a string, and if I call it with an arbitrary range (just for testing), eg. wordChart.SetSourceData("A1:C3"), it fails with a ComException(E_FAIL).
I have also found this code on a Microsoft blog:
Excel.Range tblRng = dataSheet.get_Range("A1", "B5");
Excel.ListObject tbl = dataSheet.ListObjects["Table1"];
tbl.Resize(tblRng);
which I think is meant to resize the selected dataset to the size of the worksheet. This would also be perfect for me, however, "Table1" is reported as an unknown index (maybe because I am using a non-English version of Word.)
What should I do to select the appropriate dataset?
Related
I have an Excel worksheet which has 50 Rows and 38 columns "Filled" with actual data but when I try to get the .UsedRange I am getting More than 1025 Rows and 250 columns as Used range! Please let me know how can I get only actual Used ranges with filled data and retrive the actual range data using Spreadsheetgear lib? I tried something like, but when user added some column, it's does not work.
var workbook = Factory.GetWorkbook(filePath);
var worksheet = workbook.Worksheets[0];
var cells = worksheet.UsedRange;
var headerCount = 0;
// get columns size
for (var columnCount = 0; columnCount <= range.ColumnCount; ++columnCount)
{
if (columnCount > headers.Length && string.IsNullOrEmpty(range[HeaderRow, columnCount].Text))
{
headerCount = columnCount - 1;
break;
}
}
SpreadsheetGear (and Excel itself) will include cells into the UsedRange that are empty but have formatting of some kind. For instance, if cell ABC123 has a custom NumberFormat, Font color or similar, the UsedRange will include that cell, thereby potentially blowing up your UsedRange A1:ABC123 even if the actual "value-populated" or "filled" portion of the worksheet is much smaller.
If this is a problem and you need to only include the portion of a sheet that is actually populated with cell values, below is one possible routine you might be able to use to only include cells that have cell values of some kind. It is written as an extension method off of IWorksheet to make utilization of it easier, and includes a bool flag that you can pass in so as to return either the "normal" UsedRange (including cells with other types of formatting) or the "altered" UsedRange discussed here:
public static class SGExtensionMethods
{
public static IRange GetUsedRange(this IWorksheet worksheet, bool ignoreEmptyCells)
{
IRange usedRange = worksheet.UsedRange;
if (!ignoreEmptyCells)
return usedRange;
// Find last row in used range with a cell containing data.
IRange foundCell = usedRange.Find("*", usedRange[0, 0], FindLookIn.Formulas,
LookAt.Part, SearchOrder.ByRows, SearchDirection.Previous, false);
int lastRow = foundCell?.Row ?? 0;
// Find last column in used range with a cell containing data.
foundCell = usedRange.Find("*", usedRange[0, 0], FindLookIn.Formulas,
LookAt.Part, SearchOrder.ByColumns, SearchDirection.Previous, false);
int lastCol = foundCell?.Column ?? 0;
// Return a new used range that clips of any empty rows/cols.
return worksheet.Cells[worksheet.UsedRange.Row, worksheet.UsedRange.Column, lastRow, lastCol];
}
}
A couple additional notes about this approach. It does generally take into account hidden rows or columns--meaning hidden rows or columns that have cell values will be included in the UsedRange. One exception / edge-case to this inclusion of hidden rows or columns is if AutoFilters is enabled on the worksheet. This puts the worksheet in a special "mode" that excludes hidden rows from search results. So if AutoFilters is enabled (in such cases IWorksheet.AutoFilterMode will be true), you may not be able to rely on this approach if the last row(s) or column(s) of the AutoFiltered range could possibly have been filtered out.
If I have one or more ranges how can I combine them into a range with multiple areas?
One might think to do it like this... but this won't even compile...
Excel.Worksheet sheet = workbook.ActiveSheet;
Excel.Range rng1 = (Excel.Range) sheet.get_Range(sheet.Cells[1, 1], sheet.Cells[3,42]);
Excel.Range rng2 = (Excel.Range) sheet.get_Range(sheet.Cells[5, 1], sheet.Cells[6,42]);
Excel.Range result = new Excel.Range();
result.Areas.Add(rng1);
result.Areas.Add(rng2);
UPDATE:
This is not a duplicate... this is about creating a range with two Areas... not about creating a range from two ranges each with a single cell (which would result in a range with only one area)
Derived from one of the answers in the above referred to "duplicate" question.
Note: it seems if the areas can be combined a Union will do this (for example, two adjacent rows) but if they cannot be combined like this then it creates multiple areas. (not 100% sure on this)
Also, Union can have more than two parameters... e.g. Union(range1, range2, range3, etc...)
var excelApp = Globals.ThisAddIn.Application as Excel.Application;
var sheet = workbook.ActiveSheet as Excel.Worksheet;
var range1 = sheet.get_Range(sheet.Cells[1, 1], sheet.Cells[3,42]) as Excel.Range;
var range2 = sheet.get_Range(sheet.Cells[5, 1], sheet.Cells[6,42]) as Excel.Range;
var result = excelApp.Union(range1, range2) as Excel.Range;
I have an Excel worksheet with some data. I also have a List of the column headers of the worksheet. The headers in the list are in a different order than the headers in the worksheet, and I need to reorder the Excel worksheet's columns to be the same order as the list.
List<string> dataset1Variables = new List<string>() { "Variable1", "Variable2", "Variable3", "Variable4" };
The headers of my Excel sheet may look like this:
Variable 3 | Variable 1 | Variable 4 | Variable 2
I have come across this code to shift columns but this is only for moving 1 column to a specific location. The list might be completely mixed up so I would need to shift many columns.
Excel.Range copyRange = xlWs.Range["C:C"];
Excel.Range insertRange = xlWs.Range["A:A"];
insertRange.Insert(Excel.XlInsertShiftDirection.xlShiftToRight,
copyRange.Cut());
What would be the best approach for doing this? Preferably using Interop.
If you have an empty row right above your worksheet with data, you can add matching formula right above headers. In below assuming your list is on Sheet2 range B2:B5 and your data headers start on Sheet1 range A2:D2
Excel.Workbook myBook = xlApp.Workbooks.Open(#"path\excel.xlsx");
Excel.Worksheet ws = myBook.Worksheets[1];
// You can use all dynamic ranges instead
// Excel.Range xlRng = ws.Range[ws.Cells[yourRow, firsColumn], ws.Cells[yourRow, lastColumn]];
Excel.Range xlRng = ws.Range[ws.Cells[1, 1], ws.Cells[1, 4]]; // ws.Range["A1:D1"];
xlRng.FormulaR1C1 = "=MATCH(R[-1]C,Sheet2!R2C2:$R5C2,0)";
// Below is how you can get full address for your list if it's in different workbook and replace Sheet2!R2C2:$R5C2 with rangeFullAddress
// string rangeFullAddress = xlRng.Address[true,true,Excel.XlReferenceStyle.xlR1C1,true];
xlRng.Calculate();
xlRng.Value = xlRng.Value;
After this you can just sort your data using Excel Sort by 1st row. After sorting your 1st row it would look like this: 1, 2, 3, 4. Then clear data on 1st row ws.Range["A1:D1"].Clear();.
Your sort key would be Key1: ws.Range["A1:D1"], here is c# sort example using c# to sort a column in excel only change Excel.XlSortOrientation and adjust for your range.
There are other ways to sort but this way you'll keep individual formats, comments of each cell within your data
I missed 1 important detail - that your list is not in Excel sheet, but you can add it to Excel, perhaps in temporary workbook or right on the same sheet:
object [,] columnHeaders = new object[3,0]; // or object[0,3]; if you'd like to add into 1 row
columnHeaders[0, 0] = "Variable1";
columnHeaders[1, 0] = "Variable2";
columnHeaders[2, 0] = "Variable3";
columnHeaders[3, 0] = "Variable4";
xlRng.FormulaR1C1 = columnHeaders; // xlRng would be in the above Sheet2!R2C2:$R5C2
I was trying to insert a new row at the end of a worksheet using OLEDB. The worksheet has a format table in a Range (a1:xx), with format and formula stored. But OLEDB insert does not come with any format.
I have read the post How to copy format of one row to another row in Excel with c# talking about get the format, but doesn't work for me. Also, I don't think it will get the formula.
In the Excel UI, at the lower right corner of a formatted table, a double arrow would appear, and we can drag it to expand the format table range.
Anything we could do through C#?
Thanks.
Excel.Range last = xlWS.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing);
Excel.Range RngToCopyOri = xlWS.get_Range("A1", last).EntireRow;
Excel.Range RngToCopy = RngToCopyOri.Resize[RngToCopyOri.Rows.Count + 1, RngToCopyOri.Columns.Count]; //because insert will add only 1 row, so the range would be one row larger
Excel.Range RngToInsert = xlWS.get_Range("A1", Type.Missing).EntireRow;
RngToInsert.Insert(Excel.XlInsertShiftDirection.xlShiftDown, RngToCopy.Copy(Type.Missing));
I tried to copy Range(A1,lowerleft cell) to its original location, but nothing changed.
I tried Range.resize, autofill, autoformat. All of them has sort of problems. I finally gave up using OLEDB to insert data. Instead, i used
worksheet.UsedRange.Item[rowNo,getColumnIndex(worksheet,columnTitle)]=value
private int getColumnIndex(Excel.Worksheet sheetname, string header) {
int index=0;
Excel.Range activeRange=sheetname.UsedRange;
for (int i = 1; i <= activeRange.Columns.Count; i++) {
if (header == (string)(activeRange.Item[1,i] as Excel.Range).Value) {
index = i;
}
}
if(index==0)
throw some exception you like;
return index;
}
The getColumnIndex function aims to locate the column in SELECT [column] from...
In this way, the format table will automatically expand to the range you input the value.
In Excel VBA (or if you could in C#, I'm using the Excels Object Library from .NET), how to copy a worksheet from one workbook to another sheet in another workbook. Basically, what I'm doing is copying every of my sheet into a central worksheet in another workbook and then will do all the stuff I need to do there. I tried using Range.Copy method, I gave the Destination parameter as the range of the other workbook. It worked perfectly, but there is one problem, that is every time I copy it replaces the older data in that worksheet. How do I do something like so that when I paste it pastes in the end of the sheet.
EDIT: I searched and found a way, but now when I copy the cells I get a COM exception with the message "To paste all cells from an Excel worksheet into the current worksheet, you must paste into the first cell (A1 or R1C1)."
Following is the code, it is in C#
logWorksheet = logWorkbook.ActiveSheet as Excel.Worksheet;
Excel.Range tempRange = logWorksheet.Cells[logWorksheet.Rows.Count, "A"] as Excel.Range;
tempRange = tempRange.get_End(Excel.XlDirection.xlUp);
int emptyRow;
if (tempRange.Row > 1)
emptyRow = tempRange.Row + 1;
else
emptyRow = tempRange.Row;
string copyLocationAddress = Convert.ToString(emptyRow);
Excel.Range copyLocation = logWorksheet.get_Range(
"A" + copyLocationAddress, Type.Missing) as Excel.Range;
// copy whole workbook to the central workbook
tempLogSheet.Cells.Copy(copyLocation);
-- UPDATE --
This snippet copies the cells A1:A3 of Book1 to Book2. It will find the last used cell in Book2 and will append the data underneath it.
Sub CopyRange()
Dim source As Worksheet
Dim destination As Worksheet
Dim emptyRow As Long
Set source = Workbooks("Book1.xlsx").Sheets("Sheet1")
Set destination = Workbooks("Book2.xlsx").Sheets("Sheet1")
'find empty row (actually cell in Column A)'
emptyRow = destination.Cells(destination.Rows.Count, 1).End(xlUp).Row
If emptyRow > 1 Then
emptyRow = emptyRow + 1
End If
source.Range("A1:A3").Copy destination.Cells(emptyRow, 1)
End Sub
-- OLD --
This sample copies all the sheets of Book1.xlsx to Book2.xlsx:
Workbooks("Book1.xlsx").Worksheets.Copy Before:=Workbooks("Book2.xlsx").Sheets(1)