How can ı configure "office version=15.0.0" error - c#

I'm trying to create a datagridview from sql data, make the user changes and after that with one click user will have the dataridviews data as an excel but no matter what ı tried ı keep getting that error:
"System.IO.FileNotFoundException: 'Could not load file or assembly
'office, Version=15.0.0.0, Culture=neutral,
PublicKeyToken=71e9bce111e9429c'. Sistem belirtilen dosyayı
bulamıyor.'"
btw ım using office 2016 pro and visual studio 2022
my codeblock is here :
# using System.Data;
using System.Data.SqlClient;
using Microsoft.Office.Interop.Excel;
using System.Reflection;
using System.Windows.Forms;
namespace DönüştürülecekApp
{
public partial class Pro : Form
{
public Pro()
{
InitializeComponent();
}
public void Pro_Load(object sender, EventArgs e)
{
dataGridView1.AllowUserToAddRows = true;
dataGridView1.AutoGenerateColumns = false;
dataGridView1.EnableHeadersVisualStyles = false;
var select = "Select ........";
var c = new SqlConnection("Server= ...........");
var dataAdapter = new SqlDataAdapter(select, c);
var commandBuilder = new SqlCommandBuilder(dataAdapter);
var ds = new DataSet();
dataAdapter.Fill(ds);
malzemeBindingSource.DataSource = ds.Tables[0];
}
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
ExportToExcel();
}
private void ExportToExcel()
{
string connectionString = "Server= ......";
string query = "Select ......";
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand(query, connection);
SqlDataAdapter adapter = new SqlDataAdapter(command);
System.Data.DataTable dataTable = new System.Data.DataTable();
adapter.Fill(dataTable);
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
Workbook workbook = excel.Workbooks.Add(Type.Missing);
Worksheet sheet = (Worksheet)workbook.ActiveSheet;
for (int i = 0; i < dataTable.Columns.Count; i++)
{
sheet.Cells[1, i + 1] = dataTable.Columns[i].ColumnName;
}
for (int i = 0; i < dataTable.Rows.Count; i++)
{
for (int j = 0; j < dataTable.Columns.Count; j++)
{
sheet.Cells[i + 2, j + 1] = dataTable.Rows[i][j].ToString();
}
}
workbook.SaveAs("YourFileName.xlsx", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
excel.Quit();
}
}
}
I already checked dlls and it's in that folder
:C:\Users.....nuget\packages\microsoft.office.interop.excel\15.0.4795.1001\lib\net20\Microsoft.Office.Interop.Excel.dll
ı tried to google it and none of the solutions helped me

My test environment is VS 2022 17.4.4 Winforms(.Net Framework 4.8)
Add the corresponding dll in Manage Nuget.
Because I am also using office2016, here I added MSOffice.Interop 16.0.55555.
With the right dll, you're done outputting.

Related

How to Read an Excel file to DataGridView in C#

I'm having an issue reading an excel file onto a datagridview. After running the application, it keeps telling me
"The process cannot access the file
'C:\Users\emmanuel.adefuye\Documents\ExcelTestFile.xlsx' because it is
being used by another process"
private void OpenExcelFile_Click(object sender, EventArgs e)
{
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(#"C:\\Users\\emmanuel.adefuye\\Documents\\ExcelTestFile.xlsx");
Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
Excel.Range xlRange = xlWorksheet.UsedRange;
{
//String name = "First Name";
OpenFileDialog selectedFile = new OpenFileDialog();
selectedFile.ShowDialog();
selectedFile.OpenFile();
String constr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
"C:\\Users\\emmanuel.adefuye\\Documents\\ExcelTestFile.xlsx" +
";Extended Properties='Excel 8.0;HDR=YES;';";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand oconn = new OleDbCommand("Select * From [" + selectedFile.SafeFileName + "$]", con);
con.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
DataTable data = new DataTable();
sda.Fill(data);
dataGridView1.DataSource = data;
}
int rowCount = xlRange.Rows.Count;
int colCount = xlRange.Columns.Count;
//iterate over the rows and columns and print to the console as it appears in the file
//excel is not zero based!!
for (int i = 1; i <= rowCount; i++)
{
for (int j = 1; j <= colCount; j++)
{
//new line
if (j == 1)
Console.Write("\r\n");
//write the value to the console
if (xlRange.Cells[i, j] != null && xlRange.Cells[i, j].Value2 != null)
Console.Write(xlRange.Cells[i, j].Value2.ToString() + "\t");
}
}
//cleanup
GC.Collect();
GC.WaitForPendingFinalizers();
Marshal.ReleaseComObject(xlRange);
Marshal.ReleaseComObject(xlWorksheet);
//close and release
xlWorkbook.Close();
Marshal.ReleaseComObject(xlWorkbook);
//quit and release
xlApp.Quit();
Marshal.ReleaseComObject(xlApp);
}`
There are a few different ways to read the data and manipulate it, but for your core issue of
"The process cannot access the file
'C:\Users\emmanuel.adefuye\Documents\ExcelTestFile.xlsx' because it is
being used by another process"
Your issue is that you're opening the file here
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(#"C:\\Users\\emmanuel.adefuye\\Documents\\ExcelTestFile.xlsx");
And then again attempting to access it here
OpenFileDialog selectedFile = new OpenFileDialog();
selectedFile.ShowDialog();
selectedFile.OpenFile();
String constr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
"C:\\Users\\emmanuel.adefuye\\Documents\\ExcelTestFile.xlsx" +
";Extended Properties='Excel 8.0;HDR=YES;';";
OleDbConnection con = new OleDbConnection(constr);
You could just use this great nuget package:
https://www.nuget.org/packages/NPOI/
and read excel like that:
public static XSSFWorkbook ReadExcelFile(string strFilePath)
{
XSSFWorkbook hssfwb;
using (FileStream file = new FileStream(strFilePath, FileMode.Open, FileAccess.Read))
{
hssfwb = new XSSFWorkbook(file);
}
return hssfwb;
}
private void OpenExcelFile_Click(object sender, EventArgs e)
{
var dt = ReadExcelFile(#"C:\\Users\\emmanuel.adefuye\\Documents\\ExcelTestFile.xlsx");
}

How to transfer data from a dataset to existing excel form's particular worksheet with specific row and columns in c#

I am working on a project in which I have to fetch data from DBASE files and then export the data excel form.
That excel form has more than 10 worksheets having buttons to add rows.
I have retrieved data from dbase files in required format (as required in excel form) using OLEDB.
Now the question is how to send data from datatable to excel forms specific worksheet with desired row and columns.
Also how can I send command to worksheet's button to add required rows?
thats how i fetch Data from dbase files and store it into a datatable.
private void button1_Click(object sender, EventArgs e)
{
string a = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=d:\\vat;Extended Properties =dBASE IV; User ID = Admin ;Password =";
OleDbConnection con = new OleDbConnection();
con.ConnectionString = a;
con.Open();
//MessageBox.Show(con.State.ToString());
string qu = "Select * from abc.dbf ";
OleDbDataAdapter oda = new OleDbDataAdapter(qu, con);
DataTable dt = new DataTable();
oda.Fill(dt);
this.dataGridView1.DataSource = dt;
}
There are so many examples are there to export data from data table to excel but almost in each example a new excel form is created. i have to export to an existing excel form which contain near about 10 sheets. Now i want to insert that datatable content to excel sheet named as ABC.XLS and worksheet name is A.
I hope i explained my problem.
Below answer may not satisfy your exact requirement but just verify it.
BTW sorry for the late reply as i was busy with my existing work.
Below code i have used in one of my desktop application. Hope it may help you.
public static void ExportToExcel(DataTable dt)
{
Microsoft.Office.Interop.Excel.Application excelApp = null;
try
{
// instantiating the excel application class
excelApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook currentWorkbook = excelApp.Workbooks.Add(Type.Missing);
Microsoft.Office.Interop.Excel.Worksheet currentWorksheet = (Microsoft.Office.Interop.Excel.Worksheet)currentWorkbook.ActiveSheet;
currentWorksheet.Columns.ColumnWidth = 18;
if (dt.Rows.Count > 0)
{
currentWorksheet.Cells[1, 1] = DateTime.Now.ToString("s");
int i = 1;
foreach (DataColumn dtColumn in dt.Columns)
{
// Excel work sheet indexing starts with 1
currentWorksheet.Cells[2, i] = dtColumn.Name;
++i;
}
Microsoft.Office.Interop.Excel.Range headerColumnRange = currentWorksheet.get_Range("A2", "G2");
headerColumnRange.Font.Bold = true;
headerColumnRange.Font.Color = 0xFF0000;
//headerColumnRange.EntireColumn.AutoFit();
int rowIndex = 0;
for (rowIndex = 0; rowIndex < dt.Rows.Count; rowIndex++)
{
DataRow row = dt.Rows[rowIndex];
for (int cellIndex = 0; cellIndex < row.Cells.Count; cellIndex++)
{
currentWorksheet.Cells[rowIndex + 3, cellIndex + 1] = row.Cells[cellIndex].Value;
}
}
Microsoft.Office.Interop.Excel.Range fullTextRange = currentWorksheet.get_Range("A1", "G" + (rowIndex + 1).ToString());
fullTextRange.WrapText = true;
fullTextRange.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft;
}
else
{
string timeStamp = DateTime.Now.ToString("s");
timeStamp = timeStamp.Replace(':', '-');
timeStamp = timeStamp.Replace("T", "__");
currentWorksheet.Cells[1, 1] = timeStamp;
currentWorksheet.Cells[1, 2] = "No error occured";
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
if (excelApp != null)
{
excelApp.Quit();
}
}
}
For reference just refere this MSDN Link.
Good luck...

Import Excel data to DataGridView using C#

I want to import my Excel data to DataGridView control and i already have this code:
Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook workbook = app.Workbooks.Open(file);
Microsoft.Office.Interop.Excel.Worksheet worksheet = workbook.ActiveSheet;
Range excelRange = worksheet.UsedRange;
int numberOfRows = excelRange.Rows.Count;
int numberOfCols = excelRange.Columns.Count;
for (int i = 0; i < numberOfRows; i++)
{
for (int j = 0; j < numberOfCols; j++)
{
dgvIM.Rows.Add(worksheet.Cells[i + 1, 1].Value, worksheet.Cells[i + 1, 2].Value);
}
}
This throw an System.InvalidOperationException error
and after changed to dgvIM.Rows.Add(worksheet.Cells[i, j].Value, worksheet.Cells[i, j].Value); --> System.Runtime.InteropServices.COMException
Try this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Data.OleDb;
using System.Data;
namespace WebApplication1
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnUpload_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string fileExtention = System.IO.Path.GetExtension(FileUpload1.FileName);
if (fileExtention == ".xls" || fileExtention == ".xlsx")
{
string fileName = System.IO.Path.GetFileName(FileUpload1.FileName);
FileUpload1.SaveAs(Server.MapPath("~/ExcelSheet/" + fileName));
/*Read excel sheet*/
string excelSheetFilename = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Server.MapPath("~/ExcelSheet/" + fileName) + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
OleDbConnection objcon = new OleDbConnection(excelSheetFilename);
string queryForExcel = "Select * from [UserDetail$];";
OleDbDataAdapter objda = new OleDbDataAdapter(queryForExcel, objcon);
DataSet objds = new DataSet();
objda.Fill(objds);
if (objds.Tables[0].Rows.Count > 0)
{
GridView1.DataSource = objds.Tables[0];
GridView1.DataBind();
}
}
else
{
lblMessage.Text = "Please upload excel sheet.";
}
}
}
}
}
In this first it upload excel file and that data show in gridview.
For more information refer this Excel File Upload Or Import and Display In GridView Using C# In Asp.Net

Reading of Excel File c#

Hi guys! I encountered a problem is that I have difficulty reading this Excel file into data grid view as shown above. Any help will be greatly appreciated. Thanks.
These were my codes to read Excel file but there's a error that I have difficulty troubleshooting it.
private void btnSearch_Click(object sender, EventArgs e)
{
Excel.Workbook workbook;
Excel.Worksheet NwSheet;
Excel.Range ShtRange;
Microsoft.Office.Interop.Excel.Application ExcelObj = new Microsoft.Office.Interop.Excel.Application();
OpenFileDialog filedlgExcel = new OpenFileDialog();
filedlgExcel.Title = "Select file";
filedlgExcel.InitialDirectory = #"c:\";
filedlgExcel.FileName = txtFileName.Text;
filedlgExcel.Filter = "Excel Sheet(*.xlsx)|*.xlsx|All Files(*.*)|*.*";
filedlgExcel.FilterIndex = 1;
filedlgExcel.RestoreDirectory = true;
if (filedlgExcel.ShowDialog() == DialogResult.OK)
{
workbook = ExcelObj.Workbooks.Open(filedlgExcel.FileName);
NwSheet = (Excel.Worksheet)workbook.Sheets.get_Item(1);
ShtRange = NwSheet.UsedRange; //gives the used cells in sheet
//Reading Excel file.
//Creating dataTable to read the containt of the Sheet in File.
//Set header name
for (int Cnum = 1; Cnum <= ShtRange.Columns.Count; Cnum++)
{
dt.Columns.Add(new DataColumn((ShtRange.Cells[1, Cnum] as Excel.Range).Value2.ToString()));
}
dt.AcceptChanges();
//store coumn names to array
string[] columnNames = (from dc in dt.Columns.Cast<DataColumn>() select dc.ColumnName).ToArray();
//populate fields
for (int Rnum = 2; Rnum <= ShtRange.Rows.Count; Rnum++)
{
DataRow dr = dt.NewRow();
for (int Cnum = 1; Cnum <= ShtRange.Columns.Count; Cnum++)
{
dr[Cnum - 1] = (ShtRange.Cells[Rnum, Cnum] as Excel.Range).Value2.ToString();
}
dt.Rows.Add(dr);
dt.AcceptChanges();
}
workbook.Close(true, Missing.Value, Missing.Value);
ExcelObj.Quit();
foreach (DataRow dr in dt.Rows)
{
string strEmployee = dr["Employee Name"].ToString();
obj1 = new List<employeeschedule>();
for (int i = 1; i < dt.Columns.Count; i++)
{
string period = dr[i].ToString();
string[] split = period.Split('–');
employeeschedule es = new employeeschedule();
string day = columnNames[i];
if (split[0] == "REST")
{
es.day = day;
es.startTime = "0000";
es.endTime = "0000";
es.restDay = "Yes";
}
if (split[0] == "OFF")
{
es.day = day;
es.startTime = "0000";
es.endTime = "0000";
es.restDay = "Yes";
}
else
{
es.day = day;
es.startTime = split[0];
es.endTime = split[1];
es.restDay = "No";
}
obj1.Add(es);
}
dict.Add(strEmployee, obj1);
dgvEmployeeShift.DataSource = dt;
}
}
}
The error falls on this part:
dt.Columns.Add(new DataColumn((ShtRange.Cells[1, Cnum] as Excel.Range).Value2.ToString()));
It states that "Cannot perform runtime binding on a null reference".
I love using Interop when automating Excel but for your requirement why not use OleDb? It is much faster than using Interop?
TRIED AND TESTED
private void btnSearch_Click(object sender, EventArgs e)
{
System.Data.OleDb.OleDbConnection MyCon ;
System.Data.DataSet DtSet ;
System.Data.OleDb.OleDbDataAdapter MyCommand ;
//~~> Replace this with relevant file path
MyCon = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Sample.xlsx;Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\"");
//~~> Replace this with the relevant sheet name
MyCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyCon);
MyCommand.TableMappings.Add("Table", "MyTable");
DtSet = new System.Data.DataSet();
//~~> Fill Dataset
MyCommand.Fill(DtSet);
//~~> Set Source
dataGridView1.DataSource = DtSet.Tables[0];
MyCon.Close();
}
This worked for me ...........
Browses your local folder , picks up the excel ,displays in grid view.
Using oledb is what i suggest
private void OpenFile_Click(object sender, EventArgs e)
{
OpenFileDialog openfiledialog1 = new OpenFileDialog();
if (openfiledialog1.ShowDialog()==System.Windows.Forms.DialogResult.OK)
{
this.textBox_path.Text = openfiledialog1.FileName;
}
}
private void LoadExcel_Click(object sender, EventArgs e)
{
//string pathConn = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+textBox_path.Text+";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
string pathConn = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + textBox_path.Text + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1'";
OleDbConnection conn = new OleDbConnection(pathConn);
conn.Open();
OleDbDataAdapter mydataadapter = new OleDbDataAdapter("Select * from ["+textBox_sheet.Text+"$]", conn);
DataTable dt = new DataTable();
mydataadapter.Fill(dt);
dataGridView1.DataSource = dt;
conn.Close();
}

Export data to microsoft excel from MS sql using C#

How can I use C# to export data to Microsoft Excel from MS-SQL?
Can anyone give me a sample of coding or related tutorial to connect to a database and click a button to export to Microsoft Excel?
Did you know you can do this in SQL Server Management Studio by right-clicking the database and choosing Tasks->Export Data?
using System;
using System.IO;
using System.Data.SqlClient;
using System.Data;
namespace ExporExcel
{
class Program
{
static void Main(string[] args)
{
SqlConnection con = new SqlConnection("Data Source=WINCTRL-KJ8RKFO;Initial Catalog=excel;Integrated Security=True");
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter("select * from Employee",con);
sda.Fill(dt);
ExportToExcel(dt);
}
public static void ExportToExcel(DataTable dtReport, string ExcelFilePath = null)
{
int ColumnsCount;
if (dtReport == null || (ColumnsCount = dtReport.Columns.Count) == 0)
throw new Exception("ExportToExcel: Null or empty input table!\n");
Microsoft.Office.Interop.Excel.Application Excel = new Microsoft.Office.Interop.Excel.Application();
Excel.Workbooks.Add();
Microsoft.Office.Interop.Excel._Worksheet Worksheet = Excel.ActiveSheet;
object[] Header = new object[ColumnsCount];
for (int i = 0; i < ColumnsCount; i++)
Header[i] = dtReport.Columns[i].ColumnName;
Microsoft.Office.Interop.Excel.Range HeaderRange = Worksheet.get_Range((Microsoft.Office.Interop.Excel.Range)(Worksheet.Cells[1, 1]),
(Microsoft.Office.Interop.Excel.Range)(Worksheet.Cells[1, ColumnsCount]));
int RowsCount = dtReport.Rows.Count;
object[,] Cells = new object[RowsCount, ColumnsCount];
for (int j = 0; j < RowsCount; j++)
for (int i = 0; i < ColumnsCount; i++)
Cells[j, i] = dtReport.Rows[j][i];
Worksheet.get_Range((Microsoft.Office.Interop.Excel.Range)(Worksheet.Cells[2, 1]), (Microsoft.Office.Interop.Excel.Range)(Worksheet.Cells[RowsCount + 1, ColumnsCount])).Value = Cells;
Excel.Visible = true;
}
}
}

Categories

Resources