Write Range Values from an excel file to another excel in C# - c#

I have the following code and I am trying to copy certain Range values from one Excel file to another.
I have managed to select the range from the first excel, but it does not "paste" it where I've selected the range to.
In this example, it copies it to the first cells in the second excel.
Could anyone help please?
Thank you!
Microsoft.Office.Interop.Excel.Application application = new Microsoft.Office.Interop.Excel.Application();
Workbook workbook = application.Workbooks.Open(#"Excel.xlsx", 1);
Worksheet xlWorksheet = (Worksheet)workbook.Sheets[9];
Workbook workbook1 = application.Workbooks.Open(#"Excel2.xlsx", 1);
Worksheet xlWorksheet1 = (Worksheet)workbook1.Sheets[1];
Range range1 = xlWorksheet.get_Range("C1", "C5");
object[,] valueArray = (object[,])range1.get_Value(XlRangeValueDataType.xlRangeValueDefault);
Range range2 = xlWorksheet1.get_Range("F1", "F5");
object[,] valueArray2 = (object[,])range2.get_Value(XlRangeValueDataType.xlRangeValueDefault);
for (int i = 2; i <= valueArray.GetLength(0); i++)
{
for (int j = 1; j <= valueArray.GetLength(1); j++)
{
for (int k = 1; k <= valueArray2.GetLength(0); k++)
{
for (int l = 1; l <= valueArray2.GetLength(1); l++)
{
valueArray2[i,j] = valueArray[i, j].ToString();
}
}
}
}
workbook1.Save();
workbook.Close();
workbook1.Close();
application.Quit();

Solution
Microsoft.Office.Interop.Excel.Application application = new
Microsoft.Office.Interop.Excel.Application();
Workbook workbook = application.Workbooks.Open(#"D:\Excel.xlsx", 1);
Worksheet xlWorksheet = (Worksheet)workbook.Sheets[1];
Workbook workbook1 = application.Workbooks.Open(#"D:\Excel2.xlsx", 1);
Worksheet xlWorksheet1 = (Worksheet)workbook1.Sheets[1];
Range range1 = xlWorksheet.get_Range("C1", "C5");
Range range2 = xlWorksheet1.get_Range("F1", "F5");
range1.Copy(range2);
workbook1.Save();
workbook.Save();
workbook.Close();
workbook1.Close();
application.Quit();
Thank you!

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);

C# and Reading Excel Data: Rows.Count is 0 despite having data in my excel file

I am attempting to read data from an excel file and store it in a 2D array. However, the functions that I call on my excel sheet seem to be returning 0, such as the row/column count, despite my excel sheet having data in it. Is there some sort of formatting I have to do to my excel sheet?
For example when I call the count row function on the general range, not the used range, on xlSheet, it returns 0 for some reason.
public static String[,] ReadExcelData(string fileName, string sheet)
{
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(fileName);
Excel.Worksheet xlSheet = (Excel.Worksheet)xlWorkbook.Sheets[sheet];
Excel.Range range = xlSheet.UsedRange;
int rowCount = range.Rows.Count;
int columnCount = range.Columns.Count;
String[,] dataArray = new String[rowCount, columnCount];
for (int currColumn = 1; currColumn <= columnCount; currColumn++)
{
for (int currRow = 1; currRow <= rowCount; currRow++)
{
if (range.Cells[currRow, currColumn] == null || range.Cells[currRow, currColumn].ToString() == "n/a")
{
dataArray[currRow - 1, currColumn - 1] = "";
}
else
{
dataArray[currRow - 1, currColumn - 1] = range.Cells[currRow, currColumn].ToString();
}
}
}
xlWorkbook.Close();
return dataArray;
}
I recomand ExcelDataReader if you only want to read data.
Example of ExcelDataReader: https://csharp.hotexamples.com/examples/-/ExcelDataReader/-/php-exceldatareader-class-examples.html

I want to export one specific column from my DataGrid to Excel

here is my code. I want to export Column6 and it rows to an Excel sheet. How can i do it?
Excel.Application excel = new Excel.Application();
excel.Visible = true;
object Missing = Type.Missing;
Workbook workbook = excel.Workbooks.Add(Missing);
Worksheet worksheet = (Worksheet)workbook.Sheets[1];
for (int i = 5; i < dataGridView6.Columns.Count; i++)
{
worksheet.Cells[1, 1] = dataGridView6.Columns[i].HeaderText;
}
for (int i = 0; i < dataGridView6.Rows.Count - 1; i++)
{
for (int j = 5; j < dataGridView6.Columns.Count - 1; j++)
{
worksheet.Cells[1, 1] = dataGridView6.Rows[i].Cells[j].Value.ToString();
}
}
}

Export a multidimensional string array to a new Excel spreadsheet

Using Interop I managed to import an excel document (that contains a population) to a multidimensional string array of this format:
public string[,] DataArray;
I used this method to populate the array:
try
{
Excel.Application xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Open(FilePath);
Excel._Worksheet xlWorksheet = xlWorkBook.Sheets[1];
Excel.Range xlRange = xlWorksheet.UsedRange;
rowCount = xlRange.Rows.Count;
colCount = xlRange.Columns.Count;
InitialiserTableauPopulation(rowCount, colCount);
for (int x = 1; x <= colCount; x++)
{
for (int y = 1; y <= rowCount; y++)
{
DataArray[x - 1, y - 1] = xlRange.Cells[y, x].Value2.ToString();
}
}
xlApp.Workbooks.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.message);
}
While debugging, I can see that the format is correct, for every X (column name), I have multiple Y (row data).
Example : DataArray[0,0] = NAME, DataArray[0,1] = JAMES, DataArray[0,2] = ERIC, etc.
Now what I'm trying to do is take a sample of this population, make a new multidimensional string array then export this "sample" to a new excel document : but I'm lost.
How should I proceed to export an existing two dimensional string array to a new excel sheet, keeping the same Array[column][row] format?
You just need to create a new Excel.Application, add a new Excel.Workbook and get the Excel.Worksheet from the Excel.Workbook.
Then you can iterate over your DataArray with a nested for-loop and add your values as needed using the Cell-Property of the Excel.Worksheet.
Then you save your new workbook and close it appropriately. This could look something like this
private void SaveDataArray(string excelFileName, string[,] dataArray)
{
var xlApp = new Application();
var xlWorkBook = xlApp.Workbooks.Add();
var xlWorkSheet = (Worksheet)xlWorkBook.Worksheets.Item[1];
for (int i = 0; i < dataArray.GetLength(0); i++)
{
for (int j = 0; j < dataArray.GetLength(1); j++)
{
xlWorkSheet.Cells[j + 1, i + 1] = dataArray[i, j];
}
}
xlWorkBook.SaveAs(excelFileName);
xlWorkBook.Close(true);
xlApp.Quit();
}
And then call the method like this
// create some sample data ...
string[,] dataArray = new string[1, 3];
dataArray[0, 0] = "NAME";
dataArray[0, 1] = "JAMES";
dataArray[0, 2] = "ERIC";
SaveDataArray("c:\\temp\\exceltest.xlsx", dataArray);
While I dont have a great answer for you, you didnt exactly give us the interop you are using. First I would ask why you are trying to do this the hard way? Can you not use a 3rd part lib like http://epplus.codeplex.com/

Getting Excel.WorkSheets into Same Excel.Workbook

So, after much researching and using code below in a Class the items I'm passing (a DataTable) open up in Excel. I have around 5 sheets that need to open in the same book. The code below is for the first 2. The problem is they are all opening in NEW WorkBooks -- I need them all to open in the SAME WorkBook. They are opening on the correct sheet in each new Workbook though. I thought a simple "if" statement would work, however, it is not--
Any input on how to get them consolidated into one WorkBook would be greatly appreciated and thanks in advance!
Microsoft.Office.Interop.Excel.Application oExcel = new
Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbooks oBooks;
Microsoft.Office.Interop.Excel.Sheets oSheets;
Microsoft.Office.Interop.Excel.Workbook oBook;
Microsoft.Office.Interop.Excel.Worksheet oSheet;
oExcel.Visible = true;
oExcel.DisplayAlerts = false;
oExcel.Application.SheetsInNewWorkbook = 5;
oBooks = oExcel.Workbooks;
oBook = (Microsoft.Office.Interop.Excel.Workbook)(oExcel.Workbooks.Add(Type.Missing));
oSheets = oBook.Worksheets;
if (sheetName == "Combined")
{
oSheet = (Microsoft.Office.Interop.Excel.Worksheet)oSheets.get_Item(1);
oSheet.Name = sheetName;
object[,] arr = new object[dt.Rows.Count, dt.Columns.Count];
for (int r = 0; r < dt.Rows.Count; r++)
{
DataRow dr = dt.Rows[r];
for (int c = 0; c < dt.Columns.Count; c++)
{
arr[r, c] = dr[c];
}
}
Microsoft.Office.Interop.Excel.Range c1 = (Microsoft.Office.Interop.Excel.Range)oSheet.Cells[1, 1];
Microsoft.Office.Interop.Excel.Range c2 = (Microsoft.Office.Interop.Excel.Range)oSheet.Cells[1 + dt.Rows.Count - 1, dt.Columns.Count];
Microsoft.Office.Interop.Excel.Range range = oSheet.get_Range(c1, c2);
range.Value2 = arr;
}
else if (sheetName == "Auto")
{
oSheet = (Microsoft.Office.Interop.Excel.Worksheet)oSheets.get_Item(2);
oSheet.Name = sheetName;
object[,] arr = new object[dt.Rows.Count, dt.Columns.Count];
for (int r = 0; r < dt.Rows.Count; r++)
{
DataRow dr = dt.Rows[r];
for (int c = 0; c < dt.Columns.Count; c++)
{
arr[r, c] = dr[c];
}
}
Microsoft.Office.Interop.Excel.Range c1 =
(Microsoft.Office.Interop.Excel.Range)oSheet.Cells[1, 1];
Microsoft.Office.Interop.Excel.Range c2 =
(Microsoft.Office.Interop.Excel.Range)oSheet.Cells[1 + dt.Rows.Count - 1,
dt.Columns.Count];
Microsoft.Office.Interop.Excel.Range range = oSheet.get_Range(c1, c2);
range.Value2 = arr;
}
Well your code is a bit too long to understand without comments, but if you wanna add a new sheet inside your current workbook, there is the myWorkbook.Sheets.Add() method (where myWorkbook is a ref to your current workbook).
http://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel.sheets.add(v=office.14).aspx

Categories

Resources