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.
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.
I am opening an existing Excel file with following process:
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
excel.Visible = true;
Workbook w = excel.Workbooks.Open(#"E:\ishu\Test.xlsx"
, Type.Missing,
true, 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 ws = (Worksheet)w.Worksheets[1];
Microsoft.Office.Interop.Excel.Range xlRange = ws.UsedRange;
excel.Visible = true;
Excel process gets started in task manager but no Excel window get visible.
This probably isn't the answer you are looking for, but my application uses
System.Diagnostics.Process.Start(ExcelFileToOpen);
The above is run only when the Excel file exists.
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();
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.
I use said invocation to release some Excel objects after I'm done. Is it necessary to set references to null afterwards (like in the following code) ?
var dateCol = sheet1.get_Range("C4", "C" + rowOffset);
dateCol.NumberFormat = "Text";
Marshal.ReleaseComObject(dateCol);
dateCol = null;
This is what I always use and it works very well
using Excel = Microsoft.Office.Interop.Excel;
Excel.ApplicationClass _Excel;
Excel.Workbook WB;
Excel.Worksheet WS;
try
{
_Excel = new Microsoft.Office.Interop.Excel.ApplicationClass();
WB = _Excel.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);
//do something
}
catch (Exception ex)
{
WB.Close(false, Type.Missing, Type.Missing);
throw;
}
finally
{
GC.Collect();
GC.WaitForPendingFinalizers();
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(WB);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(_Excel);
}
Do a
System.Runtime.InteropServices.Marshal.FinalReleaseComObject
On all referenced Excel objects