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();
Related
When I run a SSIS package Interactively I am getting the error Object reference not set to an instance of an object on a Script task during run time.
So I debugged the code by using break points and after going step by step the code fails at this line objExcelWbk.Close(true, Type.Missing, Type.Missing);
I have checked all my references they are all there and the imports are fine too.
The function is provided below
public void FormatExcel_DVP(string strFinalFileName, string ExcelOutputFolder, SqlConnection Conn)
{
Microsoft.Office.Interop.Excel.ApplicationClass objExcelApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
Microsoft.Office.Interop.Excel.Workbook objExcelWbk = default(Excel.Workbook);
Microsoft.Office.Interop.Excel.Worksheet objWrksheet = default(Excel.Worksheet);
string sFilePath = string.Empty;
DataSet ds = new DataSet();
string DVP_Name = string.Empty;
string sFilename = string.Empty;
int RowCount = 0;
try
{
SqlCommand cmd = new SqlCommand("select distinct LTRIM(RTRIM(DVP_Name))as DVP_Name from SBBCP_DVP_SVP Order By DVP_Name", Conn);
SqlDataAdapter _da = new SqlDataAdapter(cmd);
_da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
foreach (DataRow dr in ds.Tables[0].Rows)
{
DVP_Name = dr[0].ToString().Trim().Replace("'", "''");
sFilename = DVP_Name.Trim();
sFilePath = strFinalFileName + ExcelOutputFolder.Trim() + sFilename;
if (System.IO.File.Exists(sFilePath))
{
objExcelWbk = objExcelApp.Workbooks.Open(sFilePath.Trim(), 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);
objExcelApp.DisplayAlerts = false;
objExcelApp.Visible = false;
objWrksheet = (Excel.Worksheet)objExcelWbk.Worksheets["Details"];
((Microsoft.Office.Interop.Excel._Worksheet)objWrksheet).Activate();
Microsoft.Office.Interop.Excel.Range range;
range = (Excel.Range)objWrksheet.get_Range("A1:J1", Type.Missing);
range.Interior.ColorIndex = 15;
range.Interior.Pattern = Microsoft.Office.Interop.Excel.XlPattern.xlPatternSolid;
range.NumberFormat = "#";
range.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
range.VerticalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;
range.WrapText = true;
range.Font.Bold = true;
range.Font.Name = "Arial";
range.Font.Size = 10;
range.AutoFilter(1, Type.Missing, Microsoft.Office.Interop.Excel.XlAutoFilterOperator.xlAnd, Type.Missing, true);
RowCount = objWrksheet.UsedRange.Rows.Count;
range = objWrksheet.get_Range("A2:J2", "A" + RowCount + ":J" + RowCount);
range.WrapText = true;
FormatPivotTable(ref objExcelWbk, "Summary");
objExcelWbk.SaveAs(sFilePath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
}
}
}
objExcelWbk.Close(true, Type.Missing, Type.Missing);
objExcelApp.Quit();
}
catch (Exception e)
{
throw e;
}
}
In your code you have
for each row
{
if file exists
{
open spreadsheet.
do stuff
}
}
Close spreadsheet
the problem is that could be senarios where your spreadsheet was never opened and its trying to close it but it hadnt been set.
You should close the spreadsheet in the same scope you opened it, so in my pseudo code, after the "do stuff" - for then, if you opened it as it didnt barf or die, you have something you can close.
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 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.