I create an Excel file from c# with data validation-it seem like combo with chosen possibility
string mList1 = "=ProductCode";
oRng = oSheet.get_Range("H8", "H9");
oRng.Name = "ProductCode";
int t = dt.Rows.Count + 2;
string st = "F" + t;
oRng = oSheet.get_Range("F2", st);
oRng.Validation.Add(XlDVType.xlValidateList,
XlDVAlertStyle.xlValidAlertStop,
Missing.Value, mList1, Missing.Value);
Now I want to read the Excel file and also the chosen item from the combo. I have successfully read all the data but the data validation.
Read the data-
Microsoft.Office.Interop.Excel.Application ExcelObj = null;
ExcelObj = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook theWorkbook = ExcelObj.Workbooks.Open("C:\\Documents and Settings\\rachelg\\My Documents\\xxx.xls"
,Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing);
Microsoft.Office.Interop.Excel.Sheets sheets = theWorkbook.Worksheets;
Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)sheets.get_Item(1);
for(int x = 1; x <= 5; x++)
{
string sd = ((Microsoft.Office.Interop.Excel.Range)worksheet.Cells[x, 1]).Text.ToString();
System.Console.WriteLine(sd);//this one column
}
in different column I have the data validation but I don't know to access into it.
That seems a bit much for what is largely a simple operation.
Whilst not answering your question directly, this post I made a while back might help: accessing data record from Excel in VB.NET.
Related
I am developing a windows form application using C#. In this application the user will click a button then the program will copy some columns and rows from the clipboard and past them on a new excel workbook where user can edit the information.
In Excel, I want to block one column only which is the ID such that the user can edit all cells except
that column because this column is system generated. I am not able to get it working. below is my code
DataObject dataObj = null;
dataGridView1.SelectAll(); // copying data to clipboard
dataObj = dataGridView1.GetClipboardContent(); //
if (dataObj != null)
Clipboard.SetDataObject(dataObj);
object misValue = System.Reflection.Missing.Value;
xlexcel = new Microsoft.Office.Interop.Excel.Application();
xlexcel.DisplayFullScreen = true;
Microsoft.Office.Interop.Excel.Range CR = xlWorkSheet.get_Range("A1", "A1");
CR.Select();
xlWorkSheet.PasteSpecial(CR, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, false);
// for example block column A only
xlWorkSheet.Range["A1"].EntireColumn.Style.Locked = true;
// protect the sheet
xlWorkSheet.Protect(Type.Missing, true, true, true,
Type.Missing, Type.Missing, true, true, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing);
My problem is that after running this code and then unprotecting the sheet, the user can still edit column A. Is there a way I can protect only column A from editing?
I am using Microsoft.Office.Interop.Excel version 15. and .Net Framework 4.5.1
Any help is really appreciated.
Here try this. I don't exactly know where the issue is occurring but this might help.
DataObject dataObj = null;
dataGridView1.SelectAll(); // copying data to clipboard
dataObj = dataGridView1.GetClipboardContent(); //
if (dataObj != null)
Clipboard.SetDataObject(dataObj);
object misValue = System.Reflection.Missing.Value;
xlexcel = new Microsoft.Office.Interop.Excel.Application();
xlexcel.DisplayFullScreen = true;
Microsoft.Office.Interop.Excel.Range CR = xlWorkSheet.get_Range("A1", "A1");
CR.Select();
xlWorkSheet.PasteSpecial(CR, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, false);
// for example unblock columns B - Z only
xlWorkSheet.Range("B1", "Z1").EntireColumn.Locked = false;
// protect the sheet
xlWorkSheet.Protect(Type.Missing, true, true, true,
Type.Missing, Type.Missing, true, true, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing);
This is in no way a perfect solution to all your problems. Especially since I don't quite know how many other columns you plan to use, but this code will leave column A locked and then leave B through Z unlocked. If you have any others questions toss them in the comments.
My program, every hour, does some math calculations and saves these result into excel. When it first run(lets say 08:00 AM) it creates a excel workbook and one sheet namely "Sheet1". It saves excel and releases the COM objects. so far everything is fine.
My problem begins with second run (09:00 AM). when it tries to save new results, it overwrites existing excel file (This is OK, the way i want it) but it overwrites Sheet1 which was created in 08:00 AM. I want it to save new result in Sheet2.
In third run, i want it to save result in Sheet3
In fourth run, i want it to save result in Sheet4. so on so forth..
How can i change my code to do like above ?
thanks in advance..
My Code:
using excelApp = Microsoft.Office.Interop.Excel;
public static void Main(string[] arg)
{
while (true)
{
writeToExcel();
int wait = 3600 * 1000;
System.Threading.Thread.Sleep(Convert.ToInt32(wait));
}
}
public static void writeToExcel()
{
excelApp.Application excl = new Microsoft.Office.Interop.Excel.Application();
excl.Visible = true;
//MATH CALCULATIONS......
excelApp.Workbook wb = excl.Workbooks.Add(excelApp.XlWBATemplate.xlWBATWorksheet);
excelApp.Worksheet ws1 = (excelApp.Worksheet)wb.Worksheets[1];
excelApp.Worksheet ws2 = (excelApp.Worksheet)wb.Sheets.Add();
excelApp.Worksheet ws3 = (excelApp.Worksheet)wb.Sheets.Add();
excelApp.Worksheet ws4 = (excelApp.Worksheet)wb.Sheets.Add();
excelApp.Worksheet ws5 = (excelApp.Worksheet)wb.Sheets.Add();
excl.DisplayAlerts = false;
string fileName = string.Format(#"{0}\Data_" + DateTime.Now.Month + "-" DateTime.Now.Day + ".xlsx", Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory));
workSheet.SaveAs(fileName);
Console.WriteLine("Excel Saved Successfully!!");
excl.Quit();
// Release COM objects
if (excl != null)
System.Runtime.InteropServices.Marshal.ReleaseComObject(excl);
if (workSheet != null)
System.Runtime.InteropServices.Marshal.ReleaseComObject(workSheet);
excl = null;
workSheet = null;
GC.Collect();
}
You need to get the work book from the saved file. So at the beginning of your routine, you need a mechanism to determine if today's file already exists, if so, use the the following to get your Workbook.
Workbook WB = ExcelApp.Workbooks.Open(fileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
Hopefully this helps you see the error in your ways.
I am working on couple of C# list which need to be written to an excel workbook into two different sheets Sheet1 and Sheet2 but having no idea on how to deal with excel using interop I am using the following method
public void ExportListToExcel(List<String> listExport,string sheetName)
{
try
{
Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
worksheet = (Microsoft.Office.Interop.Excel._Worksheet)workbook.Sheets[sheetName];
worksheet = (Microsoft.Office.Interop.Excel._Worksheet)workbook.ActiveSheet;
for (int i = 1; i < listExport.Count + 1; i++)
{
//int count = 1;
worksheet.Cells[i, 1] = listExport[i - 1];
//count++;
}
string fileDestination = #"C:\Atlas Applications\AxiomParser\axiom.xls";
if (File.Exists(fileDestination))
{
File.Delete(fileDestination);
}
workbook.SaveAs(fileDestination, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
workbook.Close(true, Type.Missing, Type.Missing);
Process.Start(fileDestination);
app.Quit();
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
ExportListToExcel(listMultiRowThreeWay,"Sheet1");
ExportListToExcel(listMultiRowButterFly, "Sheet2");
I am calling the above method twice with two sheet names in the method but it give me an invalid index error when executing the method for the second time
**Is there a better way to do it?**
I have an excel with 25 or so worksheets I just want to save each worksheet as it's own new Workbook. When I run the code it copys the entire workbook just not the individual sheet. Any help would be awesome.
string FileDropLocation = #"C:\ExcelFiles";
string file_FullFileName = #"C:\ts\Conversion\v2.xlsx";
Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook workBook = app.Workbooks.Open(file_FullFileName, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
for (int i = 0; i < workBook.Worksheets.Count; i++)
{
Microsoft.Office.Interop.Excel.Worksheet workSheet = (Microsoft.Office.Interop.Excel.Worksheet)workBook.Sheets[i+1];
workSheet.SaveAs(FileDropLocation + "\\" + workSheet.Name);
}
workBook.Close();
Try this in place of your current for loop and below
foreach(Worksheet sheet in workBook.Worksheets)
{
var newbook = app.Workbooks.Add(1);
sheet.Copy(newbook.Sheets[1]);
newbook.SaveAs(FileDropLocation + "\\" + sheet.Name);
newbook.Close();
}
workBook.Close();
Just to note, I believe Workbooks.Add() places in a default blank sheet (typically Sheet1), so if you want just the copied sheet you'll have to explicitly remove it.
I know this works.
Microsoft.Office.Interop.Excel.Application xl = null;
Microsoft.Office.Interop.Excel._Workbook wb = null;
xl = new Microsoft.Office.Interop.Excel.Application();
xl.SheetsInNewWorkbook = 1;
xl.Visible = true;
wb = (Microsoft.Office.Interop.Excel._Workbook)(xl.Workbooks.Add(Type.Missing));
wb.SaveAs(FileDropLocation + "\\" + workBook.Sheets[i + 1].Name, Microsoft.Office.Interop.Excel.XlFileFormat.xlExcel8, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
wb.Close(true, Type.Missing, Type.Missing);
xl.Quit();
Microsoft.Office.Interop.Excel.Workbook destWorkbook = null;
Microsoft.Office.Interop.Excel.Worksheet workSheet = null;
Microsoft.Office.Interop.Excel.Worksheet newWorksheet = null;
destWorkbook = app.Workbooks.Open(FileDropLocation + "\\" + workBook.Sheets[i + 1].Name + ".xls", false, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
workSheet = (Microsoft.Office.Interop.Excel.Worksheet)workBook.Sheets[i + 1];
newWorksheet = (Microsoft.Office.Interop.Excel.Worksheet)destWorkbook.Worksheets.Add(Type.Missing, Type.Missing, Type.Missing, Type.Missing);
app.DisplayAlerts = false;
workSheet.Copy(Type.Missing,newWorksheet);
destWorkbook.Save();
... You need to create a new workbook in your loop and move the sheet to that workbook.
I program in VB, so i'm guessing, but the code inside your foor loop should look something like this:
Microsoft.Office.Interop.Excel.Workbook workBook2 = app.Workbooks.Add(Missing.Value)
Microsoft.Office.Interop.Excel.Worksheet workSheet = (Microsoft.Office.Interop.Excel.Worksheet)workBook.Sheets[i+1];
workSheet.Copy(workBook2.Sheets(1))
Then you can add code to delete the other sheets, etc.
Hope tihs helps.
I want to insert an Array of characters into one column of Excel. I normally use something like this to just add a normal string:
lCommand.CommandText += "\"" + row["source"].ToString().Replace("\"", "\"\"").Replace(" ", " ") + "\",";
How would I add an Array of strings to a Column of Excel? Thanks!
See this article:
Fun with Excel--setting a range of cells via an array
I recommend that you read the (short) article, but as a spoiler:
Excel.Range r = this.Range["B2", "B4"];
object[,] workingValues = new object[3, 1];
for (int i = 0; i < 3; i++)
{
workingValues[i, 0] = i + 2; // 2,3,4
}
r.Value2 = workingValues;
You can open the File with C# and write to the cell you want.
First :
using Microsoft.Office.Interop.Excel;
This require you to have COM reference for Excel.
After this you need to open the file you want and set the value. After, you can close the file.
Here is an example. You can always loop for each rows or column for your array.
_Application docExcel = new Microsoft.Office.Interop.Excel.Application();
docExcel.Visible = false;
docExcel.DisplayAlerts = false;
_Workbook workbooksExcel = docExcel.Workbooks.Open(#"C:\test.xlsx", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
_Worksheet worksheetExcel = (_Worksheet)workbooksExcel.ActiveSheet;
((Range)worksheetExcel.Cells["1", "A"]).Value2 = "aa";
((Range)worksheetExcel.Cells["1", "B"]).Value2 = "bb";
workbooksExcel.Save();
workbooksExcel.Close(false, Type.Missing, Type.Missing);
docExcel.Application.DisplayAlerts = true;
docExcel.Application.Quit();
Edit:
You can use the Dynamic keyword if you do not want all those Type.Missing parameter :
_Application docExcel = new Application{Visible = false};
dynamic workbooksExcel = docExcel.Workbooks.Open(#"C:\test.xlsx");
var worksheetExcel = (_Worksheet)workbooksExcel.ActiveSheet;
((Range)worksheetExcel.Cells["1", "A"]).Value2 = "test1";
((Range)worksheetExcel.Cells["1", "B"]).Value2 = "test2";
workbooksExcel.Save();
workbooksExcel.Close(false);
docExcel.Application.Quit();