I can't get my design table to modify when opened the line I am having the trouble is var sheet = (Excel._Worksheet)swDoc.GetDesignTable; . Essentially what I want it to do is open the window and reference the active sheet which is the "Design Table". The API does include "DesignTable" as type. I have been stuck for a while. Any help is appreciated.
//Open Solidworks Design Table
SldWorks swApp;
swApp = null;
swApp = (SldWorks)Activator.CreateInstance(Type.GetTypeFromProgID("SldWorks.Application"));
ModelDoc2 swDoc = null;
bool boolstatus = false;
swDoc = ((ModelDoc2)(swApp.ActiveDoc));
boolstatus = swDoc.Extension.SelectByID2("Design Table", "DESIGNTABLE", 0, 0, 0, false, 0, null, 0);
swDoc.InsertFamilyTableEdit();
var sheet = (Excel._Worksheet)swDoc.GetDesignTable;
//Generate Linear Guide Support in Solidworks
if (comboBox1.Text == "0")//No External Rails
{
sheet.Cells[6, 4] = "0"; //Cell Location [y-axis, x-axis]
}
Figured it out
using Excel = Microsoft.Office.Interop.Excel; //Excel Reference
public virtual Object ActiveSheet { get; set; } //Gets ActiveSheet from Excel (MUST HAVE!!!)
private void button15_Click(object sender, EventArgs e)
{
//Allows Access to Solidworks (without SDK add-in)
SldWorks swApp;
swApp = null;
swApp = (SldWorks)Activator.CreateInstance(Type.GetTypeFromProgID("SldWorks.Application"));
ModelDoc2 swDoc = null;
bool boolstatus = false;
swDoc = ((ModelDoc2)(swApp.ActiveDoc));
boolstatus = swDoc.Extension.SelectByID2("Design Table", "DESIGNTABLE", 0, 0, 0, false, 0, null, 0);
//Open Solidworks Design Table
swDoc.InsertFamilyTableEdit();
//Gets ActiveSheet to Modify
Excel.Application oXL;
Excel.Workbook oWB;
Excel.Worksheet oSheet;
//Start Excel and get Application object.
oXL = (Excel.Application)Marshal.GetActiveObject("Excel.Application");
oXL.Visible = true;
oWB = (Excel.Workbook)oXL.ActiveWorkbook;
oSheet = (Excel.Worksheet)oWB.ActiveSheet;
//Generate Linear Guide Support in Solidworks
if (comboBox1.Text == "0")//No External Rails
{
sheet.Cells[6, 4] = "0"; //Cell Location [y-axis, x-axis]
}
//Close Design Table
swDoc.CloseFamilyTable();
//Quit Excel
oXL.Quit();
}
Related
The template I am attempting to recreate is this: Template
I have started the process of attempting to recreate the template, but I am mainly having issues with cell structure and inserting data into the cells. So I am not sure if I am wasting my time trying to do something that might not be possible.
private void excelcreator()
{
Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
app.Visible = true;
app.Interactive = false;
Microsoft.Office.Interop.Excel.Workbook wb = app.Workbooks.Add(1);
Microsoft.Office.Interop.Excel.Worksheet ws = (Microsoft.Office.Interop.Excel.Worksheet)wb.Worksheets[1];
ws.Range["B7"].EntireRow.Font.Size = 14;
Range line = (Range)ws.Rows[1];
line.Insert();
ws.Range[ws.Cells[7, 2], ws.Cells[7, 4]].Merge();
app.Cells[7, 2] = "Date";
app.Interactive = true;
// AutoSet Cell Widths to Content Size
ws.Cells.Select();
ws.Cells.EntireColumn.AutoFit();
ws.PageSetup.TopMargin = 0;
ws.PageSetup.BottomMargin = 0;
ws.PageSetup.LeftMargin = 0;
ws.PageSetup.RightMargin = 0;
ws.Range[7, 2].EntireRow.Font.Bold = true;
ws.PageSetup.Orientation = XlPageOrientation.xlLandscape;
}
I am also getting an error on the line ws.Range[7, 2].EntireRow.Font.Bold = true; that says: System.Runtime.InteropServices.COMException: 'Exception from HRESULT: 0x800A03EC'"
I developed winform application that read from excel and transform it to text files.
I used Microsoft.Office.Interop.Excel library in order to work with Excel.
Here is my code:
private Excel.Application excel = null;
private Excel.Sheets sheets = null;
private Excel.Workbook excelWorkbook = null;
private Excel.Workbooks excelWorkbooks = null;
private Excel._Worksheet worksheet = null;
private Excel.Range usedRange = null;
public ExcelFacade() { }
public ExcelFacade(string fileName)
{
excel = new Excel.Application();
excelWorkbooks = excel.Workbooks;
excelWorkbook = excelWorkbooks.Open(fileName, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
sheets = excelWorkbook.Sheets;
}
After I finished work with Excel I call next method (from here):
public void Dispose()
{
foreach (Microsoft.Office.Interop.Excel.Worksheet sheet in sheets)
{
while (Marshal.ReleaseComObject(sheet) != 0) { }
}
excelWorkbook.Close();
excelWorkbooks.Close();
excel.Quit();
var chromeDriverProcesses = Process.GetProcesses().
Where(pr => pr.ProcessName.ToLower().Contains("excel"));
foreach (var process in chromeDriverProcesses)
{
process.Kill();
}
//while (Marshal.ReleaseComObject(usedRange) != 0) { }
//while (Marshal.ReleaseComObject(worksheet) != 0) { }
while (Marshal.ReleaseComObject(sheets) != 0) { }
while (Marshal.ReleaseComObject(excelWorkbook) != 0) { }
while (Marshal.ReleaseComObject(excelWorkbooks) != 0) { }
//while (Marshal.ReleaseComObject(excel.Application) != 0)
//{ }
while (Marshal.ReleaseComObject(excel) != 0) { }
usedRange = null;
worksheet = null;
excelWorkbook = null;
excelWorkbooks = null;
sheets = null;
excel = null;
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
}
}
However, if I change excel and rerun my application, the updated excel is not taken by application and it looks like it read from old excel. Such behavior is look like caching and I have no idea how to disable it.
The aforementioned is strengthened by the fact that if I change something in my code, e.g. white space, and rebuild the application, it works brilliant and take right Excel file.
Any suggestions?
As #vbnet3d said, using ClosedXML library solves all problems
I've made an application that logs data to an excel file.
I can't open the excel file until I've closed the application.
In task manager excel.exe is still running after I've closed the excel application in code.
I've tried at least 11 ways of closing excel but it doesn't work.
All the code is executed from a thread:
thread = new Thread(() => export_parameters(path));
public class xlsx_logfile
{
private Microsoft.Office.Interop.Excel._Application excel;//excel application that is used for creating excel workbooks(files)
private Microsoft.Office.Interop.Excel.Workbooks workbooks;
private Microsoft.Office.Interop.Excel._Workbook workbook;//excel workbook(file)
private Microsoft.Office.Interop.Excel._Worksheet worksheet;
private string filename;
public xlsx_logfile(string path)
{
//destructor?
excel = new Microsoft.Office.Interop.Excel.Application();
workbooks = excel.Workbooks;
workbook = workbooks.Add(Type.Missing);
worksheet = null;
worksheet = workbook.ActiveSheet;
worksheet.Name = "sensordata";
filename = path;
}
public void column_add(uint column_zerobased_index,string header, string format, double[] data)
{
Microsoft.Office.Interop.Excel.Range formatRange;
Microsoft.Office.Interop.Excel.Range c1;
//Microsoft.Office.Interop.Excel.Range c2;
column_zerobased_index = 0;
//var worksheet = workbook.ActiveSheet;
c1 = worksheet.Cells[1, column_zerobased_index+1];
//c2 = oSheet.Cells[4, 4];
formatRange = worksheet.get_Range(c1,c1);//column_zerobased_index + 1
formatRange.EntireColumn.NumberFormat = "0.0";
worksheet.Cells[1, column_zerobased_index+1].NumberFormat = "#";
worksheet.Cells[1, column_zerobased_index + 1] = header;
//todo use: https://stackoverflow.com/questions/3989122/microsoft-office-interop-excel-really-slow
for (int i = 0; i < data.Length; ++i)
{
worksheet.Cells[i + 1 + 1, column_zerobased_index+1] = data[i];
}
// Cleanup
GC.Collect();
GC.WaitForPendingFinalizers();
System.Runtime.InteropServices.Marshal.ReleaseComObject(formatRange);
System.Runtime.InteropServices.Marshal.ReleaseComObject(c1);
}
void close(string filename)
{
//worksheet = null;
//workbook.Close();
//workbook = null;
//excel = null;
//excel.Quit();
//worksheet = null;
//workbook = null;
//excel = null;
//worksheet = null;
//workbook.Close();
//workbook = null;
//excel.Quit();
//excel = null;
//worksheet = null;
//workbook.Close();
//workbook = null;
//var workbooks_local = excel.Workbooks;
//var workbook_local = workbooks_local.Open(filename);
//workbook_local.Close();
//workbooks_local.Close();
//excel.Quit();
//System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook_local);
//System.Runtime.InteropServices.Marshal.ReleaseComObject(workbooks_local);
//System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
//System.Runtime.InteropServices.Marshal.ReleaseComObject(worksheet);
//worksheet = null;
////workbook.Close();
//System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
//workbook = null;
////excel.Quit();
//System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
//excel = null;
////based on https://stackoverflow.com/questions/1526685/c-how-can-i-open-and-close-an-excel-workbook
//workbook.Close(false, filename, null);
//System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
//excel.Quit();
//System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
//workbook = null;
//excel = null;
//GC.Collect();
//GC.WaitForPendingFinalizers();
//GC.Collect();
//GC.WaitForPendingFinalizers();
//var aap = System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
//System.Runtime.InteropServices.Marshal.ReleaseComObject(worksheet);
//worksheet = null;
//workbook.Close();
//System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
//workbook = null;
//workbooks.Close();
//System.Runtime.InteropServices.Marshal.ReleaseComObject(workbooks);
//workbooks = null;
//excel.Quit();
//System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
//excel = null;
// Cleanup
GC.Collect();
GC.WaitForPendingFinalizers();
//System.Runtime.InteropServices.Marshal.FinalReleaseComObject(xlRng);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(worksheet);
workbook.Close(Type.Missing, Type.Missing, Type.Missing);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(workbook);
excel.Quit();
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(excel);
}
public void save()
{
workbook.SaveAs(filename);
close(filename);
}
}
edit: this question is different from Closing Excel Application Process in C# after Data Access because I'm executing from a thread, not a method. The provided answers didn't work.
I solved the problem myself:
private Microsoft.Office.Interop.Excel._Application excel;//excel application that is used for creating excel workbooks(files)
private Microsoft.Office.Interop.Excel._Workbook workbook;//excel workbook(file)
private Microsoft.Office.Interop.Excel._Worksheet worksheet;
excel = new Microsoft.Office.Interop.Excel.Application();
workbook = excel.Workbooks.Add();
worksheet = workbook.ActiveSheet;
workbook.Close();
excel.Quit();
GC.Collect();
GC.WaitForPendingFinalizers();
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(worksheet);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(workbook);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(excel);
worksheet = null;
workbook = null;
excel = null;
I need help reading all the rows from excel sheet as a test data in my selenium test case.
I can read only one row of an excel sheet with the following code.
//set up test for selenium
public void SetupTest()
{
selenium = new DefaultSelenium("localhost", 4444, "*googlechrome", "http://www.google.com/");
selenium.Start();
verificationErrors = new StringBuilder();
}
//Connects me to my excel sheet which is SampleTestData.xls
public void ConnectExcel()
{
excel.Application excelApp = new excel.Application();
excelApp.Visible = true;
string ExcelDataPath = #"C:\SampleTestData.xls";
excel.Workbook excelWorkBook = excelApp.Workbooks.Open(ExcelDataPath, 0, false, 5, "", "", false, excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
excel.Sheets excelSheets = excelWorkBook.Worksheets;
excel.Worksheet DataworkSheet = (excel.Worksheet)excelSheets.get_Item("Sheet1");
System.String Search1 = ((excel.Range)DataworkSheet.get_Range("A1", Type.Missing)).Value2 as string;
}
//selenium code to run the test
public void StartTest()
{
selenium.open("");
selenium.WaitForPageToLoad("100000");
selenium.Type("gbqfif", search1);
selenium.Click("btnG");
selenium.WaitForPageToLoad("100000");
}
This code lets me select only one row that contains value of search1. However, I need to iterate it such a way that it will keep running StartTest() method until all the rows(50) in the excel sheet are entered.
Any help would be appreciated.
This answer may or may not help you but I am going to take a chance and post 2 samples of code that you can use..
Example #1
using System;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Excel.Application xlApp ;
Excel.Workbook xlWorkBook ;
Excel.Worksheet xlWorkSheet ;
Excel.Range range ;
string str;
int rCnt = 0;
int cCnt = 0;
xlApp = new Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Open("csharp.net-informations.xls", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
range = xlWorkSheet.UsedRange;
for (rCnt = 1; rCnt <= range.Rows.Count; rCnt++)
{
for (cCnt = 1; cCnt <= range.Columns.Count; cCnt++)
{
str = (string)(range.Cells[rCnt, cCnt] as Excel.Range).Value2 ;
MessageBox.Show(str);
}
}
xlWorkBook.Close(true, null, null);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Unable to release the Object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
}
}
Example #2
FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read);
//1. Reading from a binary Excel file ('97-2003 format; *.xls)
IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
//...
//2. Reading from a OpenXml Excel file (2007 format; *.xlsx)
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
//...
//3. DataSet - The result of each spreadsheet will be created in the result.Tables
DataSet result = excelReader.AsDataSet();
//...
//4. DataSet - Create column names from first row
excelReader.IsFirstRowAsColumnNames = true;
DataSet result = excelReader.AsDataSet();
//5. Data Reader methods
while (excelReader.Read())
{
//excelReader.GetInt32(0);
}
//6. Free resources (IExcelDataReader is IDisposable)
excelReader.Close();
Example #3
using (FileStream fileStream = File.Open(inputFilenames[0], FileMode.Open, FileAccess.Read))
{
IExcelDataReader excelReader;
if (Path.GetExtension(inputFilenames[0]) == ".xls")
excelReader = Factory.CreateReader(fileStream, ExcelFileType.Binary);
else
excelReader = Factory.CreateReader(fileStream, ExcelFileType.OpenXml);
excelReader.NextResult();
while (excelReader.Name != this.Worksheet)
excelReader.NextResult();
while (excelReader.Read())
{
if (FirstRowHasColumnNames)
{
FirstRowHasColumnNames = false;
}
else
{
//do stuff
var test = GetColumnData(excelReader, 1);
}
}
this.Save(outputFilename);
}
you can look at this link as well
Reading from Excel File
Try this:-
//Reading from a OpenXml Excel file (2007 format; *.xlsx)
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
// DataSet - Create column names from first row
excelReader.IsFirstRowAsColumnNames = true;
DataSet result = excelReader.AsDataSet();
while (excelReader.Read())
{ // Reading from row and get columns by index
var test = excelReader.GetString(1);
}
Below is the code I'm using to load the data into an Excel worksheet, but I'm look to auto size the column after the data is loaded. Does anyone know the best way to auto size the columns?
using Microsoft.Office.Interop;
public class ExportReport
{
public void Export()
{
Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
Excel.Workbook wb;
Excel.Worksheet ws;
Excel.Range aRange;
object m = Type.Missing;
string[,] data;
string errorMessage = string.Empty;
try
{
if (excelApp == null)
throw new Exception("EXCEL could not be started.");
// Create the workbook and worksheet.
wb = excelApp.Workbooks.Add(Office.Excel.XlWBATemplate.xlWBATWorksheet);
ws = (Office.Excel.Worksheet)wb.Worksheets[1];
if (ws == null)
throw new Exception("Could not create worksheet.");
// Set the range to fill.
aRange = ws.get_Range("A1", "E100");
if (aRange == null)
throw new Exception("Could not get a range.");
// Load the column headers.
data = new string[100, 5];
data[0, 0] = "Column 1";
data[0, 1] = "Column 2";
data[0, 2] = "Column 3";
data[0, 3] = "Column 4";
data[0, 4] = "Column 5";
// Load the data.
for (int row = 1; row < 100; row++)
{
for (int col = 0; col < 5; col++)
{
data[row, col] = "STUFF";
}
}
// Save all data to the worksheet.
aRange.set_Value(m, data);
// Atuo size columns
// TODO: Add Code to auto size columns.
// Save the file.
wb.SaveAs("C:\Test.xls", Office.Excel.XlFileFormat.xlExcel8, m, m, m, m, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, m, m, m, m, m);
// Close the file.
wb.Close(false, false, m);
}
catch (Exception) { }
finally
{
// Close the connection.
cmd.Close();
// Close Excel.
excelApp.Quit();
}
}
}
Add this at your TODO point:
aRange.Columns.AutoFit();
This might be too late but if you add
worksheet.Columns.AutoFit();
or
worksheet.Rows.AutoFit();
it also works.
Also there is
aRange.EntireColumn.AutoFit();
See What is the difference between Range.Columns and Range.EntireColumn.
This method opens already created excel file, Autofit all columns of all sheets based on 3rd Row. As you can see Range is selected From "A3 to K3" in excel.
public static void AutoFitExcelSheets()
{
Microsoft.Office.Interop.Excel.Application _excel = null;
Microsoft.Office.Interop.Excel.Workbook excelWorkbook = null;
try
{
string ExcelPath = ApplicationData.PATH_EXCEL_FILE;
_excel = new Microsoft.Office.Interop.Excel.Application();
_excel.Visible = false;
object readOnly = false;
object isVisible = true;
object missing = System.Reflection.Missing.Value;
excelWorkbook = _excel.Workbooks.Open(ExcelPath,
0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "",
true, false, 0, true, false, false);
Microsoft.Office.Interop.Excel.Sheets excelSheets = excelWorkbook.Worksheets;
foreach (Microsoft.Office.Interop.Excel.Worksheet currentSheet in excelSheets)
{
string Name = currentSheet.Name;
Microsoft.Office.Interop.Excel.Worksheet excelWorksheet = (Microsoft.Office.Interop.Excel.Worksheet)excelSheets.get_Item(Name);
Microsoft.Office.Interop.Excel.Range excelCells =
(Microsoft.Office.Interop.Excel.Range)excelWorksheet.get_Range("A3", "K3");
excelCells.Columns.AutoFit();
}
}
catch (Exception ex)
{
ProjectLog.AddError("EXCEL ERROR: Can not AutoFit: " + ex.Message);
}
finally
{
excelWorkbook.Close(true, Type.Missing, Type.Missing);
GC.Collect();
GC.WaitForPendingFinalizers();
releaseObject(excelWorkbook);
releaseObject(_excel);
}
}
Have a look at this article, it's not an exact match to your problem, but suits it:
Craig Murphy - Excel – wordwrap row autosize issue