I am using excel with c# I want to merge all adjacent cells that contain a specific value using c# code.
I want to merge all the cells that contains the value (Merged cells) using c# code
i want it to be like this
First, you need to identify the cells where the range of repetitive value starts and where it ends.
Then, use this code to merge the cells:
String startRange = "A1";
String endRange = "D3";
String repetitiveValue = "Merged Cells";
Microsoft.Office.Interop.Excel.Range range = worksheet.Range[startRange, endRange];
range.Value2 = repetitiveValue;
range.Select();
range.Merge(Missing.Value);
You need to use one or the other Office library, which can help you with reading/writing spreadsheets & also with the cell merges.
Check SpreadSheetGear.net or PowerTools for OpenXml (for >= office 2007 formats)
http://ericwhite.com/blog/powertools-for-open-xml-expanded/
Related
I have an Excel file of 20 columns and there are about 150 records. I need to search for a particular string in a particular column with header "DESCRIPTION"(usually column b). The search string and column header values come from an INI File. After the search is found, I need to copy the value in column J (again from INI file) to the output file.
I am new to C#. Can somebody help me here. I tried Range.Find but I got confused.
Usually OLEDB with SQL like statements can be used to retrieve specific column or row data. Please go throgh following solutions:
http://www.c-sharpcorner.com/UploadFile/6b8651/read-excel-file-in-windows-application-using-C-Sharp/
https://www.codeproject.com/articles/1088970/read-write-excel-file-with-oledb-in-csharp-without
Hope this will give you some idea. But try to show some of your code so that members can have the better understanding of your approach. Thanks
Apart from Oledb connection you can also use ClosedXML. ClosedXML is a wrapper around OpenXML that allows you to easily work with .XLSX files.
https://github.com/ClosedXML/ClosedXML.
You can look at the documentation that'll help you understand how to search for text.
If you want to search .XLS files, then you can use the Microsoft Excel Interoperability libraries. These libraries cannot be used in a web app, are slower than ClosedXML but they support all kinds of Excel files.
You can use free version of GemBox.Spreadsheet to search for a text in both XLS and XLSX file formats. Also regarding the INI file, you can use MadMilkman.Ini.
Here is an example that you could try:
// Load INI file.
IniFile ini = new IniFile();
ini.Load("Sample.ini");
// Get INI values.
string header = ini.Sections["SampleSection"].Keys["ColumnHeaderValue"].Value;
string search = ini.Sections["SampleSection"].Keys["SearchTextValue"].Value;
string j = ini.Sections["SampleSection"].Keys["JColumnValue"].Value;
// Load XLSX file.
ExcelFile excel = ExcelFile.Load("Sample.xlsx");
ExcelWorksheet sheet = excel.Worksheets[0];
// Find column header value in first row.
ExcelColumn searchColumn = sheet.Rows[0].Cells
.First(cell => cell.ValueType == CellValueType.String && cell.StringValue == header)
.Column;
// Find search value in column.
int r, c;
searchColumn.Cells.FindText(search, false, false, out r, out c);
ExcelCell searchCell = sheet.Cells[r, c];
// Get cell from column "J" that is in the same row as cell that has search text.
ExcelCell jCell = sheet.Cells[r, ExcelColumnCollection.ColumnNameToIndex("J")];
// Set cell value.
jCell.Value = j;
// Save XLSX file.
excel.Save("Sample.xlsx");
In my C# application, I am using ClosedXml .Excel for working with excel files.
I have an excel template, where I add the template into application and add data to the excel sheet and save the excel as below,
wb = new XLWorkbook(exportOption.FileName);
---
if (wb.Worksheets.Count > 0)
{
for (int i = 0; i < wb.Worksheets.Count; i++)
{
using (var ws = wb.Worksheet(i + 1))
{
if (ws.Visibility == XLWorksheetVisibility.Visible)
{
ws.SetTabActive();
break;
}
}
}
}
try
{
wb.CalculateMode = XLCalculateMode.Auto;
wb.SaveAs(exportOption.FileName);
}
After saving the changes my excel format completely changes with other sheets as well.
For example, In one sheet i have percentage format which changes to Date format.
How can i keep the format of excel same and just insert data to other sheets.
Its common for Excel to be tricked into treating numbers as dates (as under the hood Excel stores dates as numbers). To force the cell to be a number not date try:
ws.Cell(row,col).SetValue<double>(Convert.ToDouble(val));
Here is the official documentation on ClosedXML Cell Formatting.
If you need preserve the format as percentage, eg as "#.##%" simply set the cell format:
ws.Cell(row, col).Style.NumberFormat.NumberFormatId = 10;
or untested
ws.Cell(row, col).Style.NumberFormat.Format = "0.0%";
You must select the cell Number Format from your app before saving it.
CLosedXml is a library based on OPENXML library so you must apply an OpenXml excel style Sheet to change Cells Number Format.
This is an Article that may help you
I'm not sure if using the word "dynamic" is correct. Anyway, I do have some basic understanding of using the Microsoft.Office.Interop.Excel. The problem is, I'm having about 100 excel files in a folder, each of the excel files has different sheet name, number of rows and number of columns.
As far as I understand, you need to specify the range and sheet name, i.e.:
xcel.Worksheet sheet = someExcelFiles.Sheets["SomeSheetName"] as Excel.Worksheet;
Excel.Range range = sheet.get_Range("A1:A5");
Is there anyway so that my application can read all data in all of the excel files without having to specify the sheet name and range (row and columns)?
Short answer yes. Long answer From DotNetPerls which also contains grabbing number of sheets programatically.
Range excelRange = sheet.UsedRange;
object[,] valueArray = (object[,])excelRange.get_Value(
XlRangeValueDataType.xlRangeValueDefault);
I need to know how to get the count of cells in a Row object using OpenXML. Currently, I am using
row.Descendants<Cell>().Count<Cell>()
but this is not correct at all. Any ideas what method/property gives me the count of cells?
You can get the count using one of the followings:
row.Descendants<Cell>().Count<Cell>() //The one you used
row.Elements<Cell>().Count<Cell>()
row.Count()
I tested all of them and they are working correctly. Keep in mind the following points while validating the correctness of the returned count:
- Hidden columns are included in the calculations
- Merged cells are counted separately. If your excel sheet contains 3 columns A, B & C, but A & B are merged, then the count of the cells is 3 not 2
You can extract a list of all the merged cells in a sheet using:
SpreadsheetDocument ExcelSpreadSheet = SpreadsheetDocument.Open(ReportFile, true);
WorksheetPart ExcelWSP = GetWorksheetPartByName(ExcelSpreadSheet, TemplateEntity.ExcelSheetName);
MergeCells mergeList = ExcelWSP.Worksheet.Elements<MergeCells>().First();
The merge information is saved in the Reference property, and you can access it using the following:
((MergeCell)mergeList.ElementAt(i)).Reference
I am using oledb to read data from an excel file and store it in a dataset.
My excel file contents are like as follows:
0 0 somestring somestring
500 200 somestring somestring
When i checked the contents of my data set, the values of Columns 1 & 2 are not stored as integers but rather as DateTime values.
How will I make it be stored as integer values instead of DateTime?
Have you tried adding IMEX=1 to your OLEDB connection string?
Are you sure its a number? Following could be a few options:
Right click the columns in excel and change the format to Text/Custom.
Look into the NamedRange.FormatConditions Property; change the format the data when you read it from excel, see MSDN
Or try deleting an existing format on a range:
that is,
Excel.Worksheet sheet = this.Application.ActiveSheet as Excel.Worksheet;
Excel.Range range = sheet.get_Range("A1", "A5") as Excel.Range;
//delete previous validation rules
range.Validation.Delete();
You could use a 3rd party component like SpreadsheetGear for .NET which lets you get the underlying values of cells (with IWorkbook.Worksheets["MySheet"].Cells[rowIndex, colIndex].Value) regardless of the cell format, or you can get the formatted result with IRange.Text.
You can see live ASP.NET samples here and download the free trial here.
Disclaimer: I won SpreadsheetGear LLC