Is it Possible to Recreate an Excel Template in C#? - c#

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'"

Related

C# Exporting from database to excel returns a hexadecimal error

I am reading a List from my database and I only need to export 1 column of this data into an excel sheet. However, the try catch method is catching the following Hex error "0x800AC472".
try
{
var path = #"C:\Users\Desktop\Data.xlsx";
var listOfUsers = _context.Users.ToList();
int row = 2;
Microsoft.Office.Interop.Excel.Application excel;
Microsoft.Office.Interop.Excel.Workbook excelworkBook;
Microsoft.Office.Interop.Excel.Worksheet excelSheet;
Microsoft.Office.Interop.Excel.Range excelCellrange;
excel = new Microsoft.Office.Interop.Excel.Application();
excel.Visible = false;
excel.Interactive = false;
excel.DisplayAlerts = false;
excelworkBook = excel.Workbooks.Add(Type.Missing);
excelSheet = (Microsoft.Office.Interop.Excel.Worksheet)excelworkBook.ActiveSheet;
excelSheet.Name = "Test work sheet";
excelCellrange = excelSheet.Range[excelSheet.Cells[1, 1], excelSheet.Cells[listOfUsers.Count, 1]];
excelCellrange.EntireColumn.AutoFit();
excelSheet.Cells[1, 1] = "Phone Number";
foreach (var user in listOfUsers)
{
excelSheet.Cells[row, 1] = user.PhoneNumber;
row++;
}
excelSheet.SaveAs(path);
return Ok();
}
catch (Exception ex)
{
return BadRequest(ex.Message); ;
}
Update:
Turns out the issue was in MS Office license. It was expired. Once I fixed the license everything worked out.
Based on this topic: https://social.msdn.microsoft.com/Forums/en-US/9168f9f2-e5bc-4535-8d7d-4e374ab8ff09/hresult-800ac472-from-set-operations-in-excel?forum=vsto it seems that this error is a result of excel wanting to prompt the user for some sort of input but being unable to.
Consider instead using a library like EPPlus instead. Watch out of the licensing though, it changed from LGPL to Polyform from version 5. https://www.nuget.org/packages/EPPlus/4.5.3.3

Excel worksheet won't delete [C#, WPF, VS 2010]

Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
object misValue = System.Reflection.Missing.Value;
// creating new WorkBook within Excel application
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Open(System.IO.Directory.GetCurrentDirectory() + #"\Report.xlsx");
// Get current worksheet and clear it
Microsoft.Office.Interop.Excel._Worksheet worksheet1 = workbook.Worksheets[1];
Microsoft.Office.Interop.Excel._Worksheet worksheet2 = workbook.Worksheets[2];
app.DisplayAlerts = false;
worksheet1.Delete();
worksheet2.Delete();
app.DisplayAlerts = true;
//app.Worksheets[1].Delete();
//app.Worksheets[2].Delete();
workbook.Save();
Microsoft.Office.Interop.Excel._Worksheet worksheet = (Excel.Worksheet)app.Worksheets.Add(); ;
// storing header part in Excel
for (int i = 1; i < mydatatable.Columns.Count + 1; i++)
{
worksheet.Cells[1, i] = mydatatable.Columns[i - 1].ColumnName.ToString();
}
// storing Each row and column value to excel sheet
for (int i = 0; i < mydatatable.Rows.Count; i++)
{
for (int j = 0; j < mydatatable.Columns.Count; j++)
{
worksheet.Cells[i + 2, j + 1] = mydatatable.Rows[i][j].ToString();
}
worksheet.Columns.AutoFit();
}
Excel.Range chartRange;
Excel.ChartObjects xlCharts = (Excel.ChartObjects)worksheet.ChartObjects(Type.Missing);
Excel.ChartObject myChart = (Excel.ChartObject)xlCharts.Add(10, 80, 300, 250);
Excel.Chart chartPage = myChart.Chart;
chartRange = worksheet.get_Range("C1", "E20");
chartPage.SetSourceData(chartRange);
chartPage.ChartType = Excel.XlChartType.xlColumnClustered;
chartPage.Location(Excel.XlChartLocation.xlLocationAsNewSheet,"Chart");
workbook.Save();
workbook.Close(misValue);
Marshal.ReleaseComObject(worksheet);
app.Quit();
It creates the new worksheet perfectly, but doesn't delete the old one first. I even have two codes to delete it and it doesn't. I have more than one sheet in the app.
EDIT: I just noticed that the first time I run the code it deletes the given sheets, but if I run it a second time (etc) it won't delete them anymore and gives me error, because aparently EXCEL proccess is still open in the background for some reason, altough I use "app.Quit()". Please help!
One of the problems could be that you have one worksheet when you're trying to delete it. Make sure that you're not deleting last worksheet or it won't work. So, create new one, then delete old one; not the other way around.
EDIT:
Try this code:
app.DisplayAlerts = false;
worksheetdel.Delete();
app.DisplayAlerts = true;
Source: https://stackoverflow.com/a/678795/2006048

Error while generating excel from C#

I have simple code for generating Excel which loops and produces excel sheet.
Excel.Application XlApp = null;
Excel.Workbook workbook = null;
Excel.Worksheet Ws = null;
XlApp = new Excel.Application();
XlApp.Visible = true;
workbook = XlApp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
Ws = (Excel.Worksheet)workbook.Worksheets[1];
workbook.Worksheets.Add(Missing.Value,Missing.Value,
6, Missing.Value);
for (int j = 0; j < 7; j++)
{
Ws = (Excel.Worksheet)workbook.Worksheets[j];
Ws.Activate();
Ws.Name = SheetName.ToString();//Sheetname has a Name
}
Now the problem is When we run this code everything works fine. But sometimes what happens is, at the client side one of the sheet name is not generated it skips. So our solution to them is to try generating the sheet again and then it works fine,
So my question is why does the code skip the sheetName (sometimes), although there is no problem in the code. Does it have to do anything with clients other running processes?
Try this:
Excel.Application XlApp = null;
Excel.Workbook workbook = null;
Excel.Worksheet Ws = null;
XlApp = new Excel.Application();
XlApp.Visible = true;
workbook = XlApp.Workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
// here you get the first ws, index 1
Ws = (Excel.Worksheet)workbook.Worksheets[1];
workbook.Worksheets.Add(Missing.Value, Missing.Value,
6, Missing.Value);
var SheetName = "sheet_";
// here you should start from 1 (not from 0) and include 7 in the loop count
for (int j = 1; j <= 7; j++)
{
// make sure that the ws name is unique
SheetName=String.Format("sheet_{0}",j);
Ws = (Excel.Worksheet)workbook.Worksheets[j];
Ws.Activate();
Ws.Name = SheetName;// this is already a string
}
XlApp.Quit();

Error Exporting to Excel C#

I'm getting an error when I'm exporting Excel to C#, I can't find where my code is wrong and the solution for my problem
Error :
An unhandled exception of type
'System.Runtime.InteropServices.COMException' occurred in GestãoSI.exe
Additional information: Índice inválido. (Excepção de HRESULT:
0x8002000B (DISP_E_BADINDEX))
The error appear when the code is running
// Add a workbook.
oBook = oExcel_12.Workbooks.Add(oMissing);
// Get worksheets collection
oSheetsColl = oExcel_12.Worksheets;
// Get Worksheet "Sheet1"
oSheet = (Excel_12.Worksheet)oSheetsColl.get_Item("Sheet1");
Here is all my code
public static void ExportDataGridViewTo_Excel12(DataGridView itemDataGridView)
{
Excel_12.Application oExcel_12 = null; //Excel_12 Application
Excel_12.Workbook oBook = null; // Excel_12 Workbook
Excel_12.Sheets oSheetsColl = null; // Excel_12 Worksheets collection
Excel_12.Worksheet oSheet = null; // Excel_12 Worksheet
Excel_12.Range oRange = null; // Cell or Range in worksheet
Object oMissing = System.Reflection.Missing.Value;
// Create an instance of Excel_12.
oExcel_12 = new Excel_12.Application();
// Make Excel_12 visible to the user.
oExcel_12.Visible = true;
// Set the UserControl property so Excel_12 won't shut down.
oExcel_12.UserControl = true;
// System.Globalization.CultureInfo ci = new System.Globalization.CultureInfo("en-US");
// Add a workbook.
oBook = oExcel_12.Workbooks.Add(oMissing);
// Get worksheets collection
oSheetsColl = oExcel_12.Worksheets;
// Get Worksheet "Sheet1"
oSheet = (Excel_12.Worksheet)oSheetsColl.get_Item("Sheet1");
// Export titles
for (int j = 0; j < itemDataGridView.Columns.Count; j++)
{
oRange = (Excel_12.Range)oSheet.Cells[1, j + 1];
oRange.Value2 = itemDataGridView.Columns[j].HeaderText;
}
// Export data
for (int i = 0; i < itemDataGridView.Rows.Count - 1; i++)
{
for (int j = 0; j < itemDataGridView.Columns.Count; j++)
{
oRange = (Excel_12.Range)oSheet.Cells[i + 2, j + 1];
oRange.Value2 = itemDataGridView[j, i].Value;
}
}
// Release the variables.
//oBook.Close(false, oMissing, oMissing);
oBook = null;
//oExcel_12.Quit();
oExcel_12 = null;
// Collect garbage.
GC.Collect();
}
this work for me..
oSheet = oBook.Worksheets.get_Item(index);
Since you got a non-english exception text from Excel I assume there is no sheet that is named "Sheet1", instead it has the localized name. You have to either use the loclized name or, which would be way better, just use the sheet index (should start with 1) instead of the sheet name.

Solidworks & Excel C# Referencing the Design Table

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

Categories

Resources