I am creating an application to retrieve the column names into listbox from a particular excel sheet and match the column names with the database columns and insert it into the excel data into table
Can you explain how can I can do it?
Already I have retrieved sheet names into the list box
Microsoft.Office.Interop.Excel.Application app = new ApplicationClass();
Workbook workBook = app.Workbooks.Open(#"your_file_path");
Worksheet workSheet = (Worksheet)workBook.Worksheets.get_Item(1);
Range range = workSheet.UsedRange;
for (int i = 1; i <= range.Columns.Count; i++)
{
ListBox3.Items.Add(((Excel.Range)range.Cells[2, i]).Value2);
}
See How to convert a- column number eg. 127 into an Excel column eg. AA here on Stackoverflow
Related
I want to read Excel sheet names (in workbook) using OleDB. I am filling the DataTable and assigning the sheet names to a list.
Sheet names in Excel Workbook is under
Grade 7
Grade 6
ECE
Code that I am trying is as-
DataTable schemaTable = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
List<string> lstSheets = schemaTable.AsEnumerable()
.Select(r => r.Field<string>("TABLE_NAME")).ToList();
lstClass.DataSource = lstSheets; // lstClass is a Listbox
I can read the name of sheets using this code but it has extra characters Like (' , $). sheet names retrieving are as:-
'Grade 7$'
'Grade 6$'
ECE$
I want to read just names not with special extra characters.
I have a vsto application that populates an Excel sheet.
First I populate the datatable. The next function is to create a vsto listobject:
// Populate the sheet
XlsInterop.Excel.Worksheet worksheet = (XlsInterop.Excel.Worksheet)Globals.ThisAddIn.Application.ActiveWorkbook.Worksheets.Add();
extendedWorksheet = Globals.Factory.GetVstoObject(worksheet);
XlsInterop.Excel.Range cell = extendedWorksheet.Range["A1"];
excelItemsList = extendedWorksheet.Controls.AddListObject(cell, sheetName);
excelItemsList.AutoSetDataBoundColumnHeaders = true;
excelItemsList.DataSource = dt;
excelItemsList.ListColumns[5].Range.NumberFormat = "#";
Now the problem is that in column "5" I have values like 005, 004. In Excel, the values display as 5 and 4. How can I make sure that the values in Excel show the same values as in my database?
If I change my code like:
excelItemsList.SetDataBinding(dt);
excelItemsList.ListColumns[5].Range.NumberFormat = "#";
excelItemsList.SetDataBinding(dt);
It is doing what I want, but I don't think that this is the way to go.
If you know how many leading zeros you need, you can then format the column with that.
.NumberFormat = "000";
The column would then still be evaluated as a number.
I would like to add a column that already contains cells values between two columns (or at the end) of a worksheet of an existing workbook that I load.
So I have a function that sets that "column values" I need :
private static Workbook SetIndicatorsWorkbook()
{
var workbook = new Workbook(WorkbookFormat.Excel2007MacroEnabled);
var worksheet = workbook.Worksheets.Add("Unit & Integration Tests");
//Don't worry about team and jenkinsBuilTeams variables
foreach (var team in jenkinsBuildTeams)
{
worksheet.Rows[posX].Cells[0].Value = lastnbUnitTests + lastnbIntegrationTests;
posX += 1;
}
return workbook;
}
And then in main function I want to add this column (which is workbook.worksheets[0].Columns[0] ) in a loaded workbook :
private static void Main()
{
//The workbook I need to update
Workbook workbook = Workbook.Load("file.xlsx");
Workbook temp = SetIndicatorsWorkbook();
WorksheetColumn wc = temp.Worksheets[0].Columns[0];
//The issue is that Worksheet's Columns collection has no "Insert" property
workbook.Save("file.xlsx");
}
The Columns collection of the Worksheet has an Insert method that will shift data/formatting just as would happen in Excel. This was added in the 2014 volume 2 version. You can read more about that in the help topic or the api documentation. Note I've linked to the WPF version help but the Insert method is available in the other platforms as well.
I have the following error...
System.Data.DuplicateNameException: 'A column named 'samplex' already
belongs to this DataTable.'
I have large multiple excel files that need merging into one. But all the column names are the same. So I think that is why I am getting this error.
All the data is in sheet1 one from each excel files. Searching on the net the best one I found was using Spire.Xls, sample taken from here
My code sample, using console...
using Spire.Xls;
::
::
Workbook workbook = new Workbook();
workbook.LoadFromFile(#"filea.xlsx");
Workbook workbook2 = new Workbook();
workbook2.LoadFromFile(#"fileb.xlsx");
Workbook workbook3 = new Workbook();
workbook3.LoadFromFile(#"filec.xlsx");
Worksheet sheet2 = workbook3.Worksheets[0];
DataTable dataTable = sheet2.ExportDataTable();
Worksheet sheet1 = workbook.Worksheets[0];
sheet1.InsertDataTable(dataTable, false, sheet1.LastRow + 1, 1);
//save the workbook
workbook.SaveToFile("result.xlsx");
Appreciate if anyone can help me on this?
Since you're able to get DataTable objects and all the column names are the same, I'd bet you could use DataTable.Merge() -
Workbook workbook1 = ...;
Workbook workbook2 = ...;
DataTable bookTable1 = workbook1.ExportDataTable();
DataTable booktable2 = workbook2.ExportDataTable();
bookTable1.Merge(bookTable2);
// Spire specific API calls to save bookTable1 to Excel file
The only requirement for your data is that you have a key column. To configure the DataTable with a key -
bookTable1.PrimaryKey = bookTable1.Columns("DataID" /* your key column name here */);
When I used Microsoft.Office.Interop.Excel, sample taken from here, it solve the problem regarding columns with same name. The code is long and complicated but it works but you will need Microsoft Office on the machine. Only a slight problem is that the results shows in new sheet, it doesn't go directly into sheet1. If anyone can advise me on this, it will be ideal.
I am using Visual Studio 2017.
You can use CellRange.Copy(CellRange destRange) method in Spire.XLS to merge worksheets from different workbooks into one, it won't throw the DuplicateNameException.
Refer to the following code:
//Load the first workbook
Workbook workbook1 = new Workbook();
workbook1.LoadFromFile("Sample.xlsx");
Worksheet sheet1 = workbook1.Worksheets[0];
//Load the second workbook
Workbook workbook2 = new Workbook();
workbook2.LoadFromFile("sample2.xlsx");
Worksheet sheet2 = workbook2.Worksheets[0];
int a = sheet2.LastRow;
int b = sheet2.LastColumn;
//Copy data from the 2nd row in sheet2 into sheet1
sheet2.Range[2, 1, a, b].Copy(sheet1.Range[sheet1.LastRow + 1, 1, a + sheet1.LastRow, b]);
workbook1.SaveToFile("reslut.xlsx", ExcelVersion.Version2013);
I have already tried the code and it works well on my side.
Do you know an equivalent to VBA code:
Range(Selection, Selection.End(xlToRight)).Select
In Aspose.Cells. It seems that its only possible to select the last cell in the entire row:
public Aspose.Cells.Cell EndCellInRow ( Int32 rowIndex )
Or the last cell on the right within a range:
public Aspose.Cells.Cell EndCellInRow ( Int32 startRow, Int32 endRow, Int32 startColumn, Int32 endColumn )
but then you must know more or less how big your table is going to be.
I found this from 2009: http://www.aspose.com/community/forums/permalink/196519/196405/showthread.aspx but that will not resolve my problem as I may have many tables in a sheet both horizontally and vertiacally. And I can't predict where they are going to be.
Edit1:
Sorry if this is dumb question, but ctrl+shift+arrow is such a common operation that I can't believe it would be not implemented so I'm making sure I really have to re-invent the wheel.
Aspose.Cells provides the list of tables in a worksheet using property named 'Worksheet.ListObjects'. 'ListObjects' is a colloection of 'ListObject' type which represents a Table in an excel sheet. That means if one has more than one Tables in a worksheet, the ListObjects collection will give access to every table in the worksheet very conveniently. Each 'ListObject' in turn contains a property named 'DataRange' which specifies all the cells inside a Table. For the sake of convenience DataRange can be used for following operations on a Table:
To apply styles/formatting on the cells in Table
To get the data values
Merge or move the cells in Range
Export contents
To get enumerator to traverse through Table cells
To make selection of cells from DataRange, you can traverse using DataRange to get all the cells in a Row (This could also be done for a column)
Applying any operation on Table cells like after selecting cells using Ctrl+Shift+Arrow, could be performed using a workbook object as follows:
Workbook workbook = new Workbook(new FileStream("book1.xls", FileMode.Open));
if (workbook.Worksheets[0].ListObjects.Count > 0)
{
foreach (ListObject table in workbook.Worksheets[0].ListObjects)
{
Style st = new Style();
st.BackgroundColor = System.Drawing.Color.Aqua;
st.ForegroundColor = System.Drawing.Color.Black;
st.Font.Name = "Agency FB";
st.Font.Size = 16;
st.Font.Color = System.Drawing.Color.DarkRed;
StyleFlag stFlag = new StyleFlag();
stFlag.All = true;
table.DataRange.ApplyStyle(st, stFlag);
}
}
workbook.Save("output.xls");
There is also some worthy information available in Aspose docs about Table styles and applying formatting on a ListObject. For getting last Table cell in a certain row or column, I am sure this will help:
int iFirstRowIndex = table.DataRange.FirstRow;
int iFirstColumnIndex = table.DataRange.FirstColumn;
int iLastRowIndex = table.DataRange.RowCount + iFirstRowIndex;
int iLastColumnIndex = table.DataRange.ColumnCount + iFirstColumnIndex;
for (int rowIndex = 0; rowIndex < table.DataRange.RowCount; rowIndex++)
{
//Get last cell in every row of table
Cell cell = worksheet.Cells.EndCellInColumn(rowIndex + iFirstRowIndex, rowIndex + iFirstRowIndex, (short)iFirstColumnIndex, (short)(iLastColumnIndex - 1));
//display cell value
System.Console.WriteLine(cell.Value);
}