Issue select statement on excel sheet without using OLEDB provider - c#

How can I use a select statement on an Excel sheet without using any oledb Provider? This is what I got so far by using using Excel = Microsoft.Office.Interop.Excel;. Iterating through each cell using a nested for-loop feels wrong...
// Create excel application object by calling constructor
Excel.Application xlApp = new Excel.Application();
// Open excel file using excel object
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(#"D:\Temp\file.xls");
// Open first sheet within excel document (index start at 1, not 0)
Excel._Worksheet xlWorksheet = (Excel.Worksheet)xlWorkbook.Sheets["SheetName"];
// Get used sheet bounderies
Excel.Range xlRange = xlWorksheet.UsedRange;
// Get row count
int rowCount = xlRange.Rows.Count;
// Get column count
int colCount = xlRange.Columns.Count;
//iterate over the rows and columns and print to the console as it appears in the file
for (int i = 1; i <= rowCount; i++)
{
for (int j = 1; j <= colCount; j++)
{
//new line
if (j == 1)
Console.Write("\r\n");
//write the value to the console if cell value ends on 'd'
if (xlRange.Cells[i, j] != null && xlRange.Cells[i, j].Value2 != null && (xlRange.Cells[i, j].Value2.ToString()).EndsWith("d"))
Console.Write(xlRange.Cells[i, j].Value2.ToString() + "\t");
}
}

While you could use the items interface to a range to go over all the cells, you are outputting for each row and conditionally outputting across columns, for is the right approach.
However, you could tighten the code up a little:
var rowCount = xlRange.Rows.Count;
var colCount = xlRange.Columns.Count;
for (int row = 1; row <= rowCount; ++row) {
Console.WriteLine();
for (int col = 1; col <= colCount; ++col) {
//write the value to the console if cell value ends on 'd'
if (xlRange.Cells[row, col]?.Value2?.ToString().EndsWith("d") ?? false)
Console.Write(xlRange.Cells[row, col].Value2.ToString() + "\t");
}
}

Related

I want find duplicated values in my excel sheet and change the text colors in c#

I want find duplicated values in my excel sheet and change the text colors in c#
with this code:
Excel.Application xlApp =
new Excel.Application();
//xlApp.Visible = true;
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(DtaSource1);
Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
Excel.Range xlRange = xlWorksheet.UsedRange;
int rowCount = xlRange.Rows.Count;
int colCount = xlRange.Columns.Count;
for(int k=1;k<=rowCount;k++)
{
for (int i = 1; i <= rowCount; i++)
{
for (int j = 1; j <= colCount; j++)
{
if (xlRange.Cells[i, j] != null && xlRange.Cells[i, j] == xlRange.Cells[k, 1])
{
xlRange.Cells[i, j].value = "00000";
xlWorksheet.SaveAs(DtaSource1);
}
}
}
}
but it's does not working and when i want to save changes it's throw out the error excel sheet read- only!
Here's an example of highlight duplicate and unique values in Excel by using Spire.XLS, maybe you can have a try.
//Load the Excel file
Workbook workbook = new Workbook();
workbook.LoadFromFile("Input.xlsx");
//Get the first worksheet
Worksheet sheet = workbook.Worksheets[0];
//Use conditional formatting to highlight duplicate values in range "A2:A10" with IndianRed color
ConditionalFormatWrapper format1 = sheet.Range["A2:A10"].ConditionalFormats.AddCondition();
format1.FormatType = ConditionalFormatType.DuplicateValues;
format1.BackColor = Color.IndianRed;
//Save the file
workbook.SaveToFile("HighlightDuplicates.xlsx", ExcelVersion.Version2013);

Change the Format of an Excel Column programmatically and prevent scientific Notation like exponent (E) in nubmber fields

i am generating an Excel from DataSet using the following code
int ColumnsCount;
if (DataTable == null || (ColumnsCount = DataTable.Columns.Count) == 0)
throw new Exception("ExportToExcel: Null or empty input table!\n");
// load excel, and create a new workbook
Microsoft.Office.Interop.Excel.Application Excel = new Microsoft.Office.Interop.Excel.Application();
Excel.Workbooks.Add();
// single worksheet
Microsoft.Office.Interop.Excel._Worksheet Worksheet = Excel.ActiveSheet;
object[] Header = new object[ColumnsCount];
// column headings
for (int i = 0; i < ColumnsCount; i++)
Header[i] = DataTable.Columns[i].ColumnName;
Microsoft.Office.Interop.Excel.Range HeaderRange = Worksheet.get_Range((Microsoft.Office.Interop.Excel.Range)(Worksheet.Cells[1, 1]), (Microsoft.Office.Interop.Excel.Range)(Worksheet.Cells[1, ColumnsCount]));
HeaderRange.Value = Header;
HeaderRange.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.BlanchedAlmond); //ConsoleColor.Yellow;//
HeaderRange.Font.Bold = true;
// DataCells
int RowsCount = DataTable.Rows.Count;
object[,] Cells = new object[RowsCount, ColumnsCount];
for (int j = 0; j < RowsCount; j++)
for (int i = 0; i < ColumnsCount; i++)
Cells[j, i] = (DataTable.Rows[j][i]);
Worksheet.get_Range((Microsoft.Office.Interop.Excel.Range)(Worksheet.Cells[2, 1]), (Microsoft.Office.Interop.Excel.Range)(Worksheet.Cells[RowsCount + 1, ColumnsCount])).Value = Cells;
Worksheet.Columns.AutoFit();
Worksheet.SaveAs(ExcelFilePath);
Excel.Quit();
Console.Write("Excel file saved!");
However one of my columns is being shown as 1.004E+12 instead of 1004000003451, although it a string column being returned from sql server as varchar. How can i prevent it? Can any one help?
In the end it was simple, just used .columns method
Worksheet.Columns("A").NumberFormat ="#";

C# Write in an excel with Interop file already populated

I have some data saved in some strings, now I would like to open an existing Excel file, and write these strings in order in the empty cells after the populated ones,
Example:
I have the file that in column A is written up to 10, I would like the code to check that 10 finds a datum and writes to 11 and then continue [11, B] [11, C] until I finish the strings and then save the file.
I'm using Interop
using Microsoft.Office.Interop.Excel;
using Excel = Microsoft.Office.Interop.Excel;
OpenFileDialog FileExcel = new OpenFileDialog();
if (FileExcel.ShowDialog() == DialogResult.OK)
{
try
{
var sr = new StreamReader(FileExcel.FileName);
}
catch (SecurityException ex)
{
MessageBox.Show($"Security error.\n\nError message: {ex.Message}\n\n" +
$"Details:\n\n{ex.StackTrace}");
}
}
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(FileExcel.FileName);
Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[Convert.ToInt32(comboBox1.SelectedItem)];
Excel.Range xlRange = xlWorksheet.UsedRange;
int rowCount = xlRange.Rows.Count;
int colCount = xlRange.Columns.Count;
for (int i = 1; i <= rowCount; i++)
{
for (int j = 1; j <= colCount; j++)
{
//new line
if (j == 1)
Console.Write("\r\n");
//write the value to the console
if (xlRange.Cells[i, j] != null && xlRange.Cells[i, j].Value2 != null)
Console.Write(xlRange.Cells[i, j].Value2.ToString() + "\t");
//add useful things here!
}
}

Read xlsx file on C#.net

I want to read xlsx elements and print them 4 by 4 till all element are printed but i have a problem because it prints me all elements of the file. Any idea how to print them 4 by 4
// Open the Excel file.
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(Path.GetFullPath(#"C:\Users\user\Documents\Book2.xlsx"));
// Get the first worksheet.
Excel.Worksheet xlWorksheet = (Excel.Worksheet)xlWorkbook.Sheets.get_Item(1);
// Get the range of cells which has data.
Excel.Range xlRange = xlWorksheet.UsedRange;
// Get an object array of all of the cells in the worksheet with their values.
object[,] valueArray = (object[,])xlRange.get_Value(
Excel.XlRangeValueDataType.xlRangeValueDefault);
for (int row = 1; row <= xlWorksheet.UsedRange.Rows.Count; ++row)
{
for (int col = 1; col <= xlWorksheet.UsedRange.Columns.Count; ++col)
{
Console.WriteLine(valueArray[row, col].ToString());
}
int y = xlWorksheet.UsedRange.Rows.Count / 4;
for() {
Console.WriteLine("4 addresat e para u printuan");
Console.WriteLine(" ");
}
}
Don't loop until you get to the end of columns/tows collection. Loop 1 through 4 (or 0 to 3)...
for (int row = 1; row <= 4; ++row)
{
for (int col = 1; col <= x4; ++col)
{
Console.WriteLine(valueArray[row, col].ToString());
}
}

How to iterate through Excel only extracting data from specific columns

I need to extract row data from specific columns in an xls file and add each row to a list as I iterate. I looked on this site and found How to iterate through Excel Worksheets only extracting data from specific columns, but I am not sure how to modify to allow adding to a list while going through each iteration.
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(#"C:\Temp\Sample\Sample.xls");
Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
Excel.Range xlRange = xlWorksheet.UsedRange;
int rowCount = xlRange.Rows.Count;
int colCount = xlRange.Columns.Count;
for (int i = 1; i <= rowCount; i++)
{
for (int j = 1; j <= colCount; j++)
{
//Not sure if I need to iterate this way or not
}
}
In the second loop, you want to add a conditional statement (If-then-else) code to check if you are at the column from which you want to extract your data.
In your conditional statement where your condition is met positively with the criteria for extraction, you want to insert your extraction code. For Example look at the following pseudo code:
for (int i = 1; i <= rowCount; i++)
{
for (int j = 1; j <= colCount; j++)
{
If extraction condition
then
extraction code
else
keep looking code
end
}
}
BTW you may want to look into the "Look Up" function in Excel

Categories

Resources