How to excel file import to database in c#? - c#

I have the same database table with excel in my hand.And I want to read the values ​​in this excel and save it in the database.And in the meantime excel would also like to read by providing control of whether the values ​​are empty or not.I want to do this with mvvm.If you click on the save button to check if the database is correct and I want to save.
If you excel in the empty column etc. if you want to print it to datagrid.
If not, I want to print to the database
Excel is:
ID NAME CLASS
12 JOHN 3
24 Alex 7
Database Table is:
ID NAME CLASS
I want to this excel is read and excel is insert to table.But I dont read and insert to table.I want to read excel and set datatable in excel.
I try to:
//Excel Read Code
Excel.Application app=new Excel.Application();
Excel.Workbook workbook=app.workbooks.Open(fileName,Type.Missing,Type.Missing);
Excel.Worksheet sheet=workbook.Sheets[1];
Excel.Range range=sheet.UsedRange;

`public void ReadExcel(string path){
try
{
System.Data.DataTable dt = new System.Data.DataTable();
Microsoft.Office.Interop.Excel.Application xlApp = new
Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(path);
Microsoft.Office.Interop.Excel.Worksheet xlWorksheet = xlWorkbook.Sheets[1];
Microsoft.Office.Interop.Excel.Range xlRange = xlWorksheet.UsedRange;
int rowCount = xlRange.Rows.Count;
for (int r = 2; r <= rowCount; r++)
INSERT INTO mytable (ID,NAME,CLASS)VALUES (dr[c - 1] = xlRange.Cells[r, c].Text,
xlRange.Cells[r,c+1].Text, xlRange.Cells[r,c+2].Text);
}
}
}catch(Exception ex){throw ex;}
`

Related

Copying excel worksheet to a different workbook

I'm trying to copy a worksheet to a different workbook into the last worksheet of the target workbook.
My workbooks and worksheets are created like this:
public Microsoft.Office.Interop.Excel.Workbook xlWorkbookMatrix;
public Microsoft.Office.Interop.Excel._Worksheet xlWorksheetMatrix;
I tried using worksheet.copy:
xlWorksheetMatrix.Copy(Type.Missing, xlWorkbookEvaluation.Sheets[xlWorkbookEvaluation.Sheets.Count]);
and worksheet.UsedRange.Copy:
xlWorksheetMatrix.UsedRange.Copy(xlWorkbookEvaluation.Sheets[xlWorkbookEvaluation.Sheets.Count]);
With both different methods I always get an error.
For worksheet.Copy:
System.Runtime.InteropServices.COMException occured in System.Dynamic.dll
The Copy-property of the worksheet object can't be assigned
For worksheet.UsedRange.Copy:
System.Runtime.InteropServices.COMException occured in System.Dynamic.dll
The Copy-property of the Range object can't be assigned
Having a template sheet you want to fill many times, Hope this helps :
public void test()
{
Excel.Application excelApp;
string fileTarget = "C:\target.xlsx";
string fileTemplate = "C:\template.xlsx";
excelApp = new Excel.Application();
Excel.Workbook wbTemp, wbTarget;
Excel.Worksheet sh;
//Create target workbook
wbTarget = excelApp.Workbooks.Open(fileTemplate);
//Fill target workbook
//Open the template sheet
sh = wbTarget.Worksheets["TEMPLATE"];
//Fill in some data
sh.Cells[1, 1] = "HELLO WORLD!";
//Rename sheet
sh.Name = "1. SHEET";
//Save file
wbTarget.SaveAs(fileTarget);
//Iterate through the rest of the files
for (int i = 1; i < 3; i++)
{
//Open template file in temporary workbook
wbTemp = excelApp.Workbooks.Open(fileTemplate);
//Fill temporary workbook
//Open the template sheet
sh = wbTemp.Worksheets["TEMPLATE"];
//Fill in some data
sh.Cells[1, 1] = "HELLO WORLD! FOR THE " + i + ".TH TIME";
//Rename sheet
sh.Name = i + ". SHEET";
//Copy sheet to target workbook
sh.Copy(wbTarget.Worksheets[1]);
//Close temporary workbook without saving
wbTemp.Close(false);
}
//Close and save target workbook
wbTarget.Close(true);
//Kill excelapp
excelApp.Quit();
}

Get values of Excel Cells in C# including blank cells

I'm trying to get all Excel selected range values including blank entries. What I have worked until is,when a blank is hit and then it exits the loop. I need to recognize the blank, do something with it and then go on to the next cell in the selected range.
This is my code:
// Get active excel instance
Excel.Application xlApp = (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
// Get active excel workbook
string wbn = xlApp.ActiveWorkbook.Name;
Excel.Workbook xlWorkBook = (Excel.Workbook)xlApp.ActiveWorkbook;
// Get active excel worksheet
Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlWorkBook.ActiveSheet;
// Get range of values from Excel
Microsoft.Office.Interop.Excel.Range SelectedRange = xlApp.Selection as Microsoft.Office.Interop.Excel.Range;
string[] ExcelSelection = new string[1000];
int counter = 0;
foreach (object cell in xlApp.Selection.Cells) //original loop stopping when it hits a blank cell
{
try
{
ExcelSelection[counter] = ((Excel.Range)cell).Value2.ToString().Trim();
//run query to return SAP Description for Excel Active Cell Text
dataGridView1.DataSource = GetSAPDescription(ExcelSelection[counter]);
counter++;
}
catch
{
}
}
}

C# Read data using using Microsoft.Office.Interop.Excel

I have a table of data which i need to read from excel based on user input and store it in VS as an array.
If the user enters C1, search and get the associated data:
array[0]: X1E1M101
array[1]: F2G1M202
If the user enters C2:
array[0]: X1E1M105
array[1]: F1G2M304
my data:
A B C D E
1 C1
2
3 X1 E1 M1 01
4 F2 G1 M2 02
5
6 C2
7
8 X1 E1 M1 05
9 F1 G2 M3 04
10
my code:
//I declared the Interop
using Excel = Microsoft.Office.Interop.Excel;
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
Excel.Range range;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Open(ManufacturingFile);
//xlWorkSheet = ("Default Value"); // i get an error here when trying to define the worksheet name i want to select. "Cannot impicitly convert type string to ... excel.worksheet'
xlWorkSheet = ((Excel.Worksheet)this.Application.ActiveWorkbook.Sheets[1]).Select(); // This method also I get an error.
xlWorkSheet.Activate();
I am stuck after this part as I am new to using Interop.
Hope someone can help me, I am a beginner in C# and your help is much appreciated.
You will have to open your woorkbook and worksheet , there are a number of example explaining how to do that , here is a sample
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
Excel.Range range;
string str;
int rCnt = 0;
int cCnt = 0;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Open("testone.xlsx", 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;
Microsoft.Office.Interop.Excel.Range xlFound =range.EntireRow.Find("C2",misValue, Excel.XlFindLookIn.xlValues, Excel.XlLookAt.xlPart,Excel.XlSearchOrder.xlByColumns,Excel.XlSearchDirection.xlNext,true, misValue, misValue);
if (!(xlFound == null))
{
int ID_Number = xlFound.Column;
int rownum = xlFound.Row;
Console.WriteLine(ID_Number);
Console.WriteLine(rownum);
Console.Read();
}
You could 1st get the range value of the search for example if 'C1' is at a1 the you will have to read the whole row from a(n+2) and stop when it finds an empty row.
Above code is not compiled its takenfrom here
If you're going to just read data from excel files I recommend you use the ExcelDataReader library instead, it offers better performance and doesn't leave ghost processes as opposed to the Interop one. Here's some sample code to set you up:
IExcelDataReader reader = null;
string FilePath = "PathToExcelFile";
//Load file into a stream
FileStream stream = File.Open(FilePath, FileMode.Open, FileAccess.Read);
//Must check file extension to adjust the reader to the excel file type
if (System.IO.Path.GetExtension(FilePath).Equals(".xls"))
{
reader = ExcelReaderFactory.CreateBinaryReader(stream);
}
else if (System.IO.Path.GetExtension(FilePath).Equals(".xlsx"))
{
reader = ExcelReaderFactory.CreateBinaryReader(stream);
}
if (reader != null)
{
//Fill DataSet
System.Data.DataSet result = reader.AsDataSet();
try
{
//Loop through rows for the desired worksheet
//In this case I use the table index "0" to pick the first worksheet in the workbook
foreach (DataRow row in result.Tables[0].Rows)
{
string FirstColumn = row[0].ToString();
}
}
catch
{
}
}

Excel Interop - How to get the used range data with first unused columns?

I have used the below code to retrieve data from excel. But it skips first empty columns becos of Usedrange property. How can I include that also?
Excel.Application xlApp;
Excel.Workbook xlWorkbook;
xlApp = new Excel.Application();
xlWorkbook = xlApp.Workbooks.Open(fileName);
Excel._Worksheet xlWorksheet = (Excel._Worksheet)xlApp.Workbooks[1].Worksheets[2];
Excel.Range excelCell = xlWorksheet.UsedRange;
Object[,] values = (Object[,])excelCell.Cells.Value2;
Example
UsedRange returns B,C and D. But I need A also.
I have got a solution, it may help someone.
Excel.Range excelCell = xlWorksheet.UsedRange;
Excel.Range oRng = xlWorksheet.get_Range("A1").SpecialCells(Microsoft.Office.Interop.Excel.XlCellType.xlCellTypeLastCell);
int lLastCol = oRng.Column;
int colCount = excelCell.Columns.Count;
int firstEmptyCols = lLastCol - colCount;

ListBox to Excel

Ok, so I have a class, customer, that I use to process data, and then add to a list box, like below:
//Submit data from current form
customer aCustomer = new customer(comboBox1.Text, textBox1.Text, ChannelSelecBox.Text,
PurchaserTextBox.Text, NameTextBox.Text, emailTextBox.Text, AddressTextBox.Text, StateBox.Text,
PayMethodDropDown.Text, Prod1Num.Value.ToString(), Prod2Num.Value.ToString(),
Prod3Num.Value.ToString(), Prod4Num.Value.ToString(), Prod5Num.Value.ToString(),
Prod6Num.Value.ToString(), SubTData.Text, DiscountTextBox.Text, TaxData.Text, CommentTextBox.Text,
ShipData.Text, TotalData.Text);
// Add aCustomer to ListBox
Orders.Items.Add(aCustomer);
I have a string override so that the listbox just displays the purchaser and the date.
Now I want to take all the orders entered into the list box and put, most of, this data into an excel spreadsheet, each into it's own column. How could I do this?
If you need more information or to see more of my code, let me know.
try the following;
object oOpt = System.Reflection.Missing.Value; //for optional arguments
Excel.Application oXL = new Excel.Application();
Excel.Workbooks oWBs = oXL.Workbooks;
Excel.Workbook oWB = oWBs.Add(Excel.XlWBATemplate.xlWBATWorksheet);
Excel.Worksheet oSheet = (Excel.Worksheet)oWB.ActiveSheet;
//outputRows is a List<List<object>>
int numberOfRows = outputRows.Count;
int numberOfColumns = outputRows.Max(list => list.Count);
Excel.Range oRng =
oSheet.get_Range("A1", oOpt)
.get_Resize(numberOfRows, numberOfColumns);
object[,] outputArray = new object[numberOfRows, numberOfColumns];
for (int row = 0; row < numberOfRows; row++)
{
for (int col = 0; col < outputRows[row].Count; col++)
{
outputArray[row, col] = outputRows[row][col];
}
}
oRng.set_Value(oOpt, outputArray);
oXL.Visible = true;
more details can be found at http://csharp.net-informations.com/excel/csharp-create-excel.htm
Use CSV as file format, not XLS. Excel is a pain. Especially when reading from XLS. Some incorrect cell formatting and you sometimes get the value, but sometimes not. Even in same file. Personal experience.

Categories

Resources