You are on page 1of 39

01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 ; 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59

namespace WindowsFormsApplication1 { partial class Form1 { private System.ComponentModel.IContainer components = null; protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> public void InitializeComponent() { this.button1 = new System.Windows.Forms.Button(); this.textBox1 = new System.Windows.Forms.TextBox(); this.textBox2 = new System.Windows.Forms.TextBox(); this.SuspendLayout(); // // button1 // this.button1.Location = new System.Drawing.Point(12, 97); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(75, 23); this.button1.TabIndex = 0; this.button1.Text = "Write"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(button1_Click) // // textBox1 // this.textBox1.Location = new System.Drawing.Point(12, 61); this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(100, 20); this.textBox1.TabIndex = 1; this.textBox1.Text = ""; // // textBox2 // this.textBox2.Location = new System.Drawing.Point(12, 35); this.textBox2.Name = "textBox2"; this.textBox2.Size = new System.Drawing.Size(100, 20); this.textBox2.TabIndex = 2; this.textBox1.Text = ""; // // Form1 //

60 this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F) ; 61 this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font ; 62 this.ClientSize = new System.Drawing.Size(292, 266); 63 this.Controls.Add(this.textBox2); 64 this.Controls.Add(this.textBox1); 65 this.Controls.Add(this.button1); 66 this.Name = "Form1"; 67 this.Text = "Form1"; 68 this.ResumeLayout(false); 69 this.PerformLayout(); 70 71 } 72 73 public void button1_Click(object sender, System.EventArgs e) 74 { 75 Form1 form = new Form1(); 76 MyExcel excel = new MyExcel(); 77 78 string one = form.textBox1.Text; 79 string two = form.textBox2.Text; 80 81 excel.ExcelApp(one, two); 82 } 83 84 #endregion 85 86 public System.Windows.Forms.Button button1; 87 public System.Windows.Forms.TextBox textBox1; 88 public System.Windows.Forms.TextBox textBox2; 89 } 90 } xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx 001 using System; 002 using System.Collections.Generic; 003 using System.Linq; 004 using System.Text; 005 using System.Windows; 006 using System.Windows.Controls; 007 using System.Windows.Data; 008 using System.Windows.Documents; 009 using System.Windows.Input; 010 using System.Windows.Media; 011 using System.Windows.Media.Imaging; 012 using System.Windows.Navigation; 013 using System.Windows.Shapes; 014 using System.Globalization; 015 using Excel = Microsoft.Office.Interop.Excel; 016 using System.Reflection; 017 018 019 namespace PlantDataTools 020 { 021 /// <summary> 022 /// Interaction logic for Window1.xaml 023 /// </summary> 024 public partial class Window1 : Window 025 {

026 public Window1() 027 { 028 InitializeComponent(); 029 } 030 031 private void button1_Click(object sender, RoutedEventArgs e) 032 { 033 DateTime? startDate; 034 DateTime? endDate; 035 036 if (!IsValidDate(startDateTextBox)) 037 { 038 ErrorMessageLabel.Visibility = Visibility.Visible; 039 ErrorMessageLabel.Content = "Invalid Start Date."; 040 startDate = null; 041 } 042 else 043 startDate = Convert.ToDateTime(startDateTextBox.Text); 044 if (!IsValidDate(EndDateTextBox)) 045 { 046 ErrorMessageLabel.Visibility = Visibility.Visible; 047 ErrorMessageLabel.Content = "Invalid End Date."; 048 endDate = null; 049 } 050 else 051 endDate = Convert.ToDateTime(EndDateTextBox.Text); 052 053 if (startDate != null && endDate != null) 054 { 055 GetData((DateTime)startDate, (DateTime)endDate); 056 } 057 } 058 059 060 061 private bool IsValidDate(TextBox textBox) 062 { 063 if (!string.IsNullOrEmpty(textBox.Text)) 064 { 065 string[] formats = { "M/d/yyyy", "M/d/yy" }; 066 DateTime value; 067 068 if (!DateTime.TryParseExact(textBox.Text, formats, new C ultureInfo("en-US"), DateTimeStyles.None, out value)) 069 { 070 return false; 071 } 072 } 073 return true; 074 } // --- END IsVaidDate --075 076 private void GetData(DateTime startTime, DateTime endTime) 077 { 078 079 //Declare Excel Objects... 080 Excel.Application xlApplication; 081 Excel._Workbook xlWorkbook; 082 Excel._Workbook xlDataWorkbook; 083 Excel._Worksheet xlWorksheet; 084 Excel._Worksheet xlDataWorksheet;

085 Excel.Range xlWorkingRange; 086 Excel.Range xlDataRange; 087 object missing = Missing.Value; 088 089 //Declare method variables... 090 decimal grossGeneration; 091 decimal netGeneration; 092 System.Array myValues; 093 decimal[] decArray; 094 095 //Set currentDate to startDate. 096 DateTime currentDate = startTime; 097 098 int totalDays = (endTime - startTime).Days + 1; 099 100 ErrorMessageLabel.Content = totalDays.ToString(); 101 ErrorMessageLabel.Visibility = Visibility.Visible; 102 103 try 104 { 105 //Start Excel and get Application Object. 106 xlApplication = new Excel.Application(); 107 xlApplication.Visible = true; 108 109 xlWorkbook = (Excel._Workbook)(xlApplication.Workbooks.A dd(missing)); 110 xlWorksheet = (Excel._Worksheet)xlWorkbook.Worksheets["s heet1"]; 111 xlWorksheet.Cells[1, 1] = "Date"; 112 xlWorksheet.Cells[1, 2] = "U1 CT Gross"; 113 xlWorksheet.Cells[1, 3] = "U1 ST Gross"; 114 xlWorksheet.Cells[1, 4] = "U2 CT Gross"; 115 xlWorksheet.Cells[1, 5] = "U2 ST Gross"; 116 xlWorksheet.Cells[1, 6] = "U3 CT Gross"; 117 xlWorksheet.Cells[1, 7] = "U3 ST Gross"; 118 xlWorksheet.Cells[1, 8] = "Line 1 Net"; 119 xlWorksheet.Cells[1, 9] = "Line 2 Net"; 120 xlWorksheet.Cells[1, 10] = "Gross Output"; 121 xlWorksheet.Cells[1, 11] = "Net Output"; 122 123 for (int i = 1; i <= totalDays; i++) 124 { 125 xlDataWorkbook = (Excel._Workbook)(xlApplication.Wor kbooks.Open( 126 @"N:\Everyone\DISPATCH FOLDER\TVA Daily Report\" + 127 currentDate.ToString("yyyy") + @"\" + 128 currentDate.ToString("MM") + " " + 129 currentDate.ToString("MMMM") + " " + 130 currentDate.ToString("yy") + @"\" + 131 currentDate.ToString("MM") + "-" + 132 currentDate.ToString("dd") + "-" + 133 currentDate.ToString("yy") + " TVA Report.xls", 134 missing, missing, missing, missing, missing, mis sing, missing, 135 missing, missing, missing, missing, missing, mis sing, missing)); 136 137 xlDataWorksheet = (Excel._Worksheet)xlDataWorkbook.W orksheets["Hourly Data"];

138 139 xlWorksheet.Cells[i + 1, 1] = currentDate.ToShortDat eString(); 140 xlWorksheet.Cells[i + 1, 2] = xlDataWorksheet.Cells[ 61, 2]; 141 xlWorksheet.Cells[i + 1, 3] = xlDataWorksheet.Cells[ 61, 3]; 142 xlWorksheet.Cells[i + 1, 4] = xlDataWorksheet.Cells[ 61, 6]; 143 xlWorksheet.Cells[i + 1, 5] = xlDataWorksheet.Cells[ 61, 7]; 144 xlWorksheet.Cells[i + 1, 6] = xlDataWorksheet.Cells[ 61, 10]; 145 xlWorksheet.Cells[i + 1, 7] = xlDataWorksheet.Cells[ 61, 11]; 146 xlWorksheet.Cells[i + 1, 8] = xlDataWorksheet.Cells[ 61, 14]; 147 xlWorksheet.Cells[i + 1, 9] = xlDataWorksheet.Cells[ 61, 16]; 148 xlWorksheet.Cells[i + 1, 10] = "=SUM(B" + (i + 1).To String() + ":G" + (i + 1).ToString() + ")"; 149 xlWorksheet.Cells[i + 1, 11] = "=SUM(H" + (i + 1).To String() + ":I" + (i + 1).ToString() + ")"; 150 151 currentDate = currentDate.AddDays(1); 152 153 xlDataWorkbook.Close(missing, missing, missing); 154 155 } 156 157 } 158 catch (Exception e) 159 { 160 string errorMessage=""; 161 errorMessage = string.Concat(errorMessage, e.Message); 162 errorMessage = string.Concat(errorMessage, " Line: "); 163 errorMessage = string.Concat(errorMessage, e.Source); 164 165 MessageBox.Show(errorMessage, "Error"); 166 } 167 } 168 169 170 } 171 } xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx 01 using System; 02 using System.Collections.Generic; 03 using System.Linq; 04 using System.Text; 05 using System.Data.OleDb; 06 using System.Windows.Forms; 07 08 namespace MyTry 09 { 10 static class Checking 11 { 12 static public int Check_Method() 13 {

14 string sConn = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Doc uments and Settings\Cp\My Documents\MyExample.xlsm" + @";Extended Properties=""E xcel 12.0 Macro;HDR=Yes;ImpoertMixedTypes=Text;TypeGuessRows=0"""; 15 16 OleDbConnection conn = new OleDbConnection(sConn); 17 string command_check = "select * from [ID]"; 18 OleDbCommand cmd = new OleDbCommand(command_check, conn) ; 19 try 20 { 21 conn.Open(); 22 return Convert.ToInt16(cmd.ExecuteScalar()); 23 //x = 24 //MessageBox.Show(x.ToString()); 25 } 26 catch (OleDbException ex) 27 { 28 MessageBox.Show(ex.ToString ()); 29 return 0; 30 } 31 finally 32 { 33 conn.Close(); 34 35 } 36 37 } 38 } 39 } xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx private void btnImport_Click(object sender, EventArgs e) 02 { 03 04 try 05 { 06 07 if (Checking.Check_Method() == 1)//Calling my Checking c lass function 08 { 09 10 conn.ConnectionString = @"Provider=Microsoft.ACE.OLE DB.12.0;Data Source=C:\Documents and Settings\Cp\My Documents\MyExample.xlsm" + @";Extended Properties=""Excel 12.0 Macro;HDR=Yes;ImpoertMixedTypes=Text;TypeGue ssRows=0"""; 11 12 string comm_1 = "select * from [MyTable]"; 13 OleDbCommand command = new OleDbCommand(comm_1, conn ); 14 System.Data.DataTable table_1 = new System.Data.Data Table(); 15 16 dsDvds.Clear(); 17 adapter.SelectCommand = command; 18 OleDbCommandBuilder Builder_1 = new OleDbCommandBuil der(adapter); 19 20 21 22 adapter.Fill(dsDvds, "MyTable");

23 table_1 = dsDvds.Tables["MyTable"]; 24 dtgViewTab1.DataSource = table_1; 25 tblNameBs.DataSource = table_1; 26 27 } 28 else if (Checking.Check_Method() == 2) 29 { 30 //............... 31 } 32 33 34 catch (Exception ex) 35 { 36 MessageBox.Show("Error Occurs: "+ex .ToString ()); 37 } 38 } xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx 01 Add reference to Microsoft.Office.Interop.Excel 02 using System.Globalization; 03 using System.Runtime.InteropServices; 04 using Microsoft.Office.Interop.Excel; 05 using Excel=Microsoft.Office.Interop.Excel; 06 07 ............................................ 08 public void test() 09 { 10 try 11 { 12 Excel.Application xlApp = new Excel.Application(); 13 Excel.Workbook xlWorkBook = default(Excel.Workbook); 14 Excel.Worksheet xlWorkSheet = default(Excel.Worksheet); 15 Excel.Range xlRange = default(Excel.Range); 16 Excel.Range xlUsedRange = default(Excel.Range); 17 18 // get the current instance of Excel application: 19 xlApp = (Excel.Application)Marshal.GetActiveObject("Excel.Applic ation"); 20 21 xlWorkBook = xlApp.ActiveWorkbook; 22 List<string> sheets= new List<string>(); 23 24 foreach (Excel.Worksheet sheet in xlWorkBook.Worksheets) 25 { 26 sheets.Add(sheet.Name); 27 } 28 string msg =""; 29 foreach (string sh in sheets) 30 msg=msg+sh+"\n"; 31 MessageBox.Show("Therea are sheets in this workbook:\n" + msg); 32 xlWorkSheet = (Excel.Worksheet)xlApp.ActiveSheet; 33 xlRange = (Excel.Range)xlWorkSheet.Cells; 34 xlUsedRange=(Excel.Range)xlWorkSheet.UsedRange; 35 36 // convert used range to table, see Google 37 //Test only: 38 39 MessageBox.Show("Active Workbook: "+ xlWorkBook.FullName + "\n" + 40 "Active Sheet Name: "+ xlWorkSheet.Name + "\n" +

41 "Used Range Rows Count: "+ xlUsedRange.Rows.Coun t.ToString() + "\n"+ 42 "Used Range Columns Count: "+ xlUsedRange.Columns .Count.ToString() ); 43 //Move to Sheet3: 44 ((Excel._Worksheet)xlWorkBook.Sheets[3]).Activate(); <-Underscor e character is important in this case! 45 // get active sheet 46 xlWorkSheet = (Excel.Worksheet)xlApp.ActiveSheet; 47 MessageBox.Show("Now you was moving to sheet:\n" + xlWorkSheet.N ame ); 48 //'Close witout changes: 49 xlWorkBook.Close(false,xlWorkBook.FullName,null); 50 xlApp.Quit(); 51 releaseObject(xlWorkBook); 52 releaseObject(xlWorkSheet); 53 releaseObject(xlApp); 54 55 56 } 57 catch (System.Exception ex) 58 { 59 MessageBox.Show(ex.ToString()); 60 } 61 62 } 63 64 private void releaseObject(object obj) 65 { 66 try 67 { 68 System.Runtime.InteropServices.Marshal.FinalReleaseComObject(obj ); 69 obj = null; 70 } 71 catch (System.Exception ex) 72 { 73 74 System.Diagnostics.Debug.Print(ex.ToString()); 75 obj = null; 76 } 77 finally 78 { 79 GC.Collect(); 80 } 81 } xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx I have some strange problem with textboxes.In my Excel file I have 3 textboxes c alled(txt_1.txt_2 and txt_3). I put them all in group called "Group 99". Let's say txt_1.value=1,txt_2.value=2, and txt_3.value=3.Then I save excel file and reopen it,everything works good. In my textboxes I see values (1,2 and 3).If I change tht values to let's say 5, 6 and 7,(txt_1.value=5......) and then I open my c# application,read the data fr om my textboxes which are in Group 9901 int i = 0; 02 foreach (Excel.Shape shp in xlWorkSheet.Shapes.Item("Gro up 99").GroupItems) 03 { 04 05 Excel.OLEObject excelOleObject1 = (Excel.OLEObject)s

hp.OLEFormat.Object; 06 if (i == 0) 07 { 08 csharp_txt_1.Text = excelOleObject1.Object.GetTy pe().InvokeMember("Text", System.Reflection.BindingFlags.GetProperty, null, exce lOleObject1.Object, null).ToString(); 09 10 11 } 12 else if (i == 1) 13 csharp_txt_2.Text = excelOleObject1.Object.GetTy pe().InvokeMember("Text", System.Reflection.BindingFlags.GetProperty, null, exce lOleObject1.Object, null).ToString(); 14 else if (i == 2) 15 csharp_txt_3.Text = excelOleObject1.Object.GetTy pe().InvokeMember("Text", System.Reflection.BindingFlags.GetProperty, null, exce lOleObject1.Object, null).ToString(); 16 i++; 17 }

So far everything is great.Next what I do is just releasing my objects1 releaseObject(xlWorkBook); 2 releaseObject(xlWorkSheet); 3 releaseObject(xlApp); I didnt save and close my woorkbook cuz I need to do tht manually in Excel.Now the weird part: So I switch to my Excel file, and what I see in my textboxes are old values,txt _1.text=1,txt_2.text=2,txt_3.text=3(instead txt_1.text=5....(6,7)). After I select one of my three textboxes, a real value is come back,but when i click somewhere else again fake value pop up again.This fake values are only dis played,they dont exist,cuz if i do something with this textboxes like Msg(txt_1. text) i will get a real value(5 in this case).Also If i call my c# application a gain my c# textboxes contains a real values(5,6,7).So fake values in excel are d isplayed but textboes contains a real value. After I use debug i find out tht this happens after this :1 WorkBook); 2 releaseObject(xlWorkSheet); 3 releaseObject(xlApp); releaseObject(xl

So i comment tht and it worked fine,until I havent stopped c# program by clicki ng "X" in right up corner. Any help or ideas pls? xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx 01 [HttpPost] 02 public ActionResult Index(HttpPostedFileBase excelFile) 03 { 04 if (excelFile != null) 05 { 06 string pathToExcelFile = "PATH HERE"; 07 08 //Create a connection string to access the Excel file using the ACE provider. 09 //This is for Excel 2007. 2003 uses an older driver.

10 var connectionString = string.Format("Provider=Microsoft.ACE.OLE DB.12.0;Data Source={0};Extended Properties=Excel 12.0;", pathToExcelFile); 11 12 //Fill the dataset with information from the Hoja1 worksheet. 13 var adapter = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", co nnectionString); 14 var ds = new DataSet(); 15 adapter.Fill(ds, "results"); 16 DataTable data = ds.Tables["results"]; 17 18 //Create a new list of People. 19 var people = new List<Person>(); 20 21 for (int i = 0; i < data.Rows.Count - 1; i++) 22 { 23 Person newPerson = new Person(); 24 newPerson.Id = data.Rows[i].Field<double?>("Id"); 25 newPerson.Name = data.Rows[i].Field<string>("Name"); 26 newPerson.LastName = data.Rows[i].Field<string>("LastName"); 27 newPerson.DateOfBirth = data.Rows[i].Field<DateTime?>("DateO fBirth"); 28 29 people.Add(newPerson); 30 } 31 } 32 } xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx 01 [HttpPost] 02 public ActionResult Index(HttpPostedFileBase excelFile) 03 { 04 if (excelFile != null) 05 { 06 string pathToExcelFile = "PATH HERE"; 07 08 //Create a connection string to access the Excel file using the ACE provider. 09 //This is for Excel 2007. 2003 uses an older driver. 10 var connectionString = string.Format("Provider=Microsoft.ACE.OLE DB.12.0;Data Source={0};Extended Properties=Excel 12.0;", pathToExcelFile); 11 12 //Fill the dataset with information from the Hoja1 worksheet. 13 var adapter = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", co nnectionString); 14 var ds = new DataSet(); 15 adapter.Fill(ds, "results"); 16 DataTable data = ds.Tables["results"]; 17 18 //Create a new list of People. 19 var people = new List<Person>(); 20 21 for (int i = 0; i < data.Rows.Count - 1; i++) 22 { 23 Person newPerson = new Person(); 24 newPerson.Id = data.Rows[i].Field<double?>("Id"); 25 newPerson.Name = data.Rows[i].Field<string>("Name"); 26 newPerson.LastName = data.Rows[i].Field<string>("LastName"); 27 newPerson.DateOfBirth = data.Rows[i].Field<DateTime?>("DateO fBirth"); 28

29 people.Add(newPerson); 30 } 31 } 32 } xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx I also found some code when searching other threads. I think it should work, but I get an error when I try and compile. It states that "The type or namespace na me 'Excel' does not exist in the namespace 'Microsoft.Office.Interop' (are you m issing an assembly reference?)". I have added the Microsoft Office reference and the Microsoft Excel Object reference. What am I missing?01 [/code] 02 using System; 03 using System.Collections.Generic; 04 using System.ComponentModel; 05 using System.Data; 06 using System.Drawing; 07 using System.Text; 08 using System.Data.SqlClient; 09 10 using Excel = Microsoft.Office.Interop.Excel; 11 using System.Windows.Forms; 12 //borrowed from http://vb.net-informations.com/excel-2007/vb.net_export_ from_database_to_excel.htm 13 14 15 namespace WindowsApplication5 16 { 17 public partial class Form1 : Form 18 { 19 public Form1() 20 { 21 InitializeComponent(); 22 } 23 24 private void button1_Click(object sender, EventArgs e) 25 { 26 27 SqlConnection cnn; 28 string connectionString; 29 string sql; 30 int i; 31 int j; 32 33 Excel.Application xlApp; 34 Excel.Workbook xlWorkBook; 35 Excel.Worksheet xlWorkSheet; 36 object misValue = System.Reflection.Missing.Value; 37 38 xlApp = new Excel.ApplicationClass(); 39 xlWorkBook = xlApp.Workbooks.Add(misValue); 40 xlWorkSheet = (Excel.Worksheet)xlWorkBook.Sheets.get_Item(1) ; 41 42 connectionString = "data source=.\\SQLEXPRESS;" + "initial c atalog=Northwind;user id=yourID;password=yourPassword;"; 43 cnn = new SqlConnection(connectionString); 44 cnn.Open(); 45 sql = "SELECT * FROM Employees"; 46 SqlDataAdapter dscmd = new SqlDataAdapter(sql, cnn); 47 DataSet ds = new DataSet();

48 dscmd.Fill(ds); 49 50 for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++) 51 { 52 for (j = 0; j <= ds.Tables[0].Columns.Count - 1; j++) 53 { 54 Excel.Range xlRange = (Excel.Range)xlWorkSheet.Cells [i + 1, j + 1]; 55 xlRange.Value2 = ds.Tables[0].Rows[i].ItemArray[j].T oString(); 56 } 57 } 58 59 xlWorkSheet.SaveAs("C:\\vbexcel.xls", misValue, misValue, mi sValue, misValue, misValue, misValue, misValue, misValue, misValue); 60 xlWorkBook.Close(true, "C:\\vbexcel.xls", misValue); 61 xlApp.Quit(); 62 63 releaseObject(xlApp); 64 releaseObject(xlWorkBook); 65 releaseObject(xlWorkSheet); 66 67 cnn.Close(); 68 69 MessageBox.Show("You can find the file C:\\vbexcel.xls"); 70 } 71 72 private void releaseObject(object obj) 73 { 74 try 75 { 76 System.Runtime.InteropServices.Marshal.ReleaseComObject( obj); 77 obj = null; 78 } 79 catch (Exception ex) 80 { 81 MessageBox.Show(ex.Message); 82 obj = null; 83 } 84 finally 85 { 86 GC.Collect(); 87 } 88 } 89 } 90 } Was This Post Helpful? xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx I am working on the same thing. My code is able to read from excel, but it isn't able to write back to the .xls file. I am not sure if I am missing something, o r if it is even possible to write the way I have it set up. Any help is apprecia ted. view source print

?01 private void button1_Click(object sender, EventArgs e) 02 { 03 04 05 // To load the excel file into the DataTable object 06 07 string filename = "data.xls"; 08 string tableName = "Sheet1"; 09 10 DataTable myTable = new DataTable(); 11 string databaseConnection = @"Provider=Microsoft.Jet.OLEDB.4.0; Data Sou rce=" + filename + "; Extended Properties=Excel 8.0;"; 12 string databaseCommand = "SELECT * FROM [" + tableName + "$]"; 13 14 using (OleDbConnection connection = new OleDbConnection(databaseConnecti on)) 15 { 16 OleDbCommand command = new OleDbCommand(databaseCommand, connection) ; 17 connection.Open(); 18 using (OleDbDataReader reader = command.ExecuteReader()) 19 { 20 myTable.Load(reader); 21 } 22 } 23 24 // Read into a string 25 string myString = Convert.ToString(myTable.Rows[0][1]); 26 System.Console.WriteLine(myString); 27 System.Console.WriteLine(myTable.Rows[0][1]); 28 29 30 // Write to a cell WRITES TO TABLE, BUT WILL NOT TO .XLS FILE 31 //PLEASE HELP! 32 myString = "xxx"; 33 myTable.Rows[0][1] = myString; 34 System.Console.WriteLine(myString); 35 System.Console.WriteLine(myTable.Rows[0][1]); 36 } Was This Post Helpful? xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx Microsoft Technologies Answers Home Microsoft Technologies RSS Reading Excel From C#

You can read data from Excel using the JET OLEDB provider. See the URL below for the necessary connection string, and a link to a KB article with further information ... http://www.carlprothman.net/Default.aspx?tabid=87#OLEDBProviderForMicrosoftJetEx cel --

Brendan Reynolds wrote in message news:9226766e-a1d5-400c-8d3c-8ffc566bec50@discussions.microsoft.com... > Hi > > Can anyone help me how to read values in Excel in C# . So that Once I > read I can send them to DataBase. My excel file Test.xls in ("C:\") > > Thanks > Doss > 64 Answers Found Answer 1 Hi Can anyone help me how to read values in excel in C# . So that Once I read I can send them to DataBase. My excel file Test.xls in ("C:\") Thanks Doss

Answer 2 I would guess: open Excel from your program, and have Excel read the data. Search for Visual Studio Tools for Office (VSTO) for the details. Answer 3 His Doss, Create a reference in your project to excel Objects Library. The exc el object library can be added in the COM tab of adding reference dialog. I hope the following code in your menu click event method will help you a lot to achi eve your need. this.openFileDialog1.FileName = "*.xls"; if (this.openFileDialog1.ShowDialog() == DialogResult.OK) { Excel.Workbook theWorkbook = ExcelObj.Workbooks.Open( openFileDialog1.FileName, 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true); Excel.Sheets sheets = theWorkbook.Worksheets; Excel.Worksheet worksheet = (Excel.Worksheet)sheets.get_Item(1); for (int i = 1; i <= 10; i++) { Excel.Range range = worksheet.get_Range("A"+i.ToString(), "J" + i.ToString( )); System.Array myvalues = (System.Array)range.Cells.Value; string[] strArray = ConvertToStringArray(myvalues); } } Cheers,

Daya Anand, PSPIndia Answer 4 If you are using a dynamically generated excel file then you can use the follow ing:

Excel.Sheets sheets = m_Excel.Worksheets; Excel.Worksheet worksheet = (Excel.Worksheet)sheets.get_Item(1); System.Array myvalues; Excel.Range range = worksheet.get_Range("A1", "E1".ToString()); myvalues = (System.Array)range.Cells.Value;

Thanks

Answer 5 If you don't want to use the Excel COM objects, you can use OleDb. It takes a li ttle setup in your Excel document. Basically, you need to define "named objects" in Excel that are synonymous to tables in a database. The first row of the name d object are the column headers. To set up a named object, first select the rang e of cells (your "table," with the first row being the column headers), then go to menu Insert->Names->Define. Name your object and press "Add." Now you have an object which can be read by ADO.NET. Now for the C# (this example assumes I have an Excel file at C:\Book1.xls and a named object in this workbook called "MyObject"): using System.Data; using System.Data.OleDb; ... OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Dat a Source=C:\Book1.xls;Extended Properties=Excel 8.0"); OleDbDataAdapter da = new OleDbDataAdapter("select * from MyObject", con); DataTable dt = new DataTable(); da.Fill(dt);

You can use SQL to query the data in your named object. Answer 6

When I try to do this, I keep getting "Old format or invalid type library" I added "Microsoft excel 10.0" as reference and use the following code Excel.ApplicationClass excel = new Excel.ApplicationClass(); Excel.Workbook workbook = excl.Workbooks.Open(openFileDialog.FileName.toString() , null, null, null, null, null, null, null, null, null, null, null, null, null, null). I also don't know what all these parameters should be. Answer 7 I just started working on an application which performs this action. Feel free t o use the following code. //Start up excel to read the excel file in question Microsoft.Office.Interop.Excel.Application ExcelObj = null;ExcelObj = new Micros oft.Office.Interop.Excel.Application(); if (ExcelObj == null) { MessageBox.Show("ERROR: EXCEL couldn't be started!"); System.Windows.Forms.Application.Exit(); } Microsoft.Office.Interop.Excel.Workbook theWorkbook = ExcelObj.Workbooks.Open(op enFileDialog.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); Microsoft.Office.Interop.Excel.Sheets sheets = theWorkbook.Worksheets; Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.E xcel.Worksheet)sheets.get_Item(1); for(int x = 1; x <= 29; x++) { Microsoft.Office.Interop.Excel.Range range = worksheet.get_Range("A"+x.ToString( ), "I" + x.ToString()); System.Array myvalues = (System.Array)range.Cells.get_Value(range.); string[] strArray = ConvertToStringArray(myvalues); } Sorry about the bad formatting, I don't know how to use this forum that well yet . Answer 8 Hellow, I'used these things a couple of months ago for an application I made. While tryi ng to adapt the application now I cannot open the excel file anymore. Does anyb ody hase any notice of changes in the Excel object? public ExcelDB() { try { excel.Open(Application.StartupPath+"\\MAILING.XLS");

excel.Range(); string file = Application.StartupPath+"\\MAILING.XLS"; sbConn.Append(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+file); sbConn.Append(";Extended Properties="); sbConn.Append(Convert.ToChar(34)); sbConn.Append("Excel 8.0;HDR=NO;IMEX=2"); sbConn.Append(Convert.ToChar(34)); cnExcel = new OleDbConnection(sbConn.ToString()); cmdExcel = new OleDbCommand("Select * From Clientlist",cnExcel); } catch { MessageBox.Show("Ernstige fout, klantenbestand niet gevonden!","Error 03",System .Windows.Forms.MessageBoxButtons.OK,System.Windows.Forms.MessageBoxIcon.Stop); } } public void FillList() { try { Cursor.Current = Cursors.WaitCursor; cnExcel.Open(); drExcel = cmdExcel.ExecuteReader(); while(drExcel.Read()) { if(drExcel["Name"].ToString() != "") { LogicControl.form.clientList.Items.Add(drExcel["Name"].ToString()); string[] listArray = {drExcel["Name"].ToString(), drExcel["Address"].ToString(), drExcel["City"].ToString(), drExcel["Phone"].ToString(), drExcel["Fax"].ToString(), drExcel["VAT"].ToString() }; lvi = new ListViewItem(listArray); LogicControl.form.klantenList.Items.Add(lvi); } } drExcel.Close(); cnExcel.Close(); Cursor.Current = Cursors.Arrow; } catch { excel.Quit(); MessageBox.Show("Ernstige fout, foutief klantenbestand!","Error 05",System.Windo ws.Forms.MessageBoxButtons.OK,System.Windows.Forms.MessageBoxIcon.Stop); } } Answer 9 Hello There I'm Using the Same Way but i'm Facing a problem and i hope to find a solution he re objWorkbook = objExcel.Workbooks.Open(MapPath("\" & MyFilePath ))

objWorkbook.Unprotect() objSheets = objWorkbook.Sheets() objRange = objSheets.Application.Cells and i tried to add a row using these tow lines once for the first and the second time i used the second one .. 'objSheets.Application.Cells.Insert(Excel.XlDirection.xlDown, 1) 'objRange.Insert(Excel.XlInsertShiftDirection.xlShiftDown) but a new EXCEPTION appear which says "To prevent possible loss of data, Microsoft Office Excel cannot shift nonblank cells off the worksheet. Try to locate the last nonblank cell by pressing CTRL+END, and delete or clear a ll in cells between the last cell and the end of your data. Then select cell A1 and save your workbook to reset the last cell used. Or, you can move the data to a new location and try again." Any one Know how to solve this ? Please note i'm using a predisigned Excel "Formatted File " Answer 10 I have the same problem, and I'm not using code. I insert one line, and it does fine. When I insert a second line, I get the same message you listed in a modal box ("To prevent possible loss of data, microsoft Office Excel cannot shift no nblank cells off the worksheet."). If I save the file, I can then insert the add itional line, but then I get the same message again when I try to insert another line. My sheet is large, but not that large; the last line is around 60k, leavi ng several thousand empty lines. Looks like Excel is trying to be too smart, and messing up in the process. I hav e Excel 2003 (with all updates), so it's not something a newer version would fix . Maybe an older version will fix it... There are no references to the message, that I could find, in Excel documentatio n or the KB. Answer 11 Found a reference, worded slightly differently so it wasn't in the original sear ch results. (http://support.microsoft.com/kb/305568) You probably have formatting the entire length of a column/row, such as a cell b order. If you go to the edge of the used area, select the rest of the sheet, and remove the border, you should eliminate the problem. It's an instant problem caused by selecting a row/column and adding an edge bord er to it - after that point, you can't insert additional rows more that one at a time.

Microsoft - Please fix the problem. Excel sees this formatting as content, but i t is not. (Excel even adds the border back if the row is deleted!) Answer 12 Hi There, I also facing the same problem but it bit of different . I wanted to read the data in Excel Sheet Eg: If Data is there for columns A,B,C,D .. wanted to read the data 'A' and 'B' 'A' and 'C' after that I wanted to generate the Charts .. any suggestions or solutions. Thanks-Aparna Answer 13 can any body give any solution for the above query please Thanks-Aparna Answer 14 "To prevent possible loss of data, Microsoft Office excel cannot shift nonblank cells off the worksheet. Try to locate the last nonblank cell by pressing CTRL+END, and delete or clear all in cells between the last cell and the end of your data. Then select cell A1 and save your workbook to reset the last cell used. Or, you can move the data to a new location and try again." This usually happens when Excel thinks that there is information in the very last row. If you hit Ctrl+End, you may find that it shoots all the way down to row 65536 or something like that. Clear the contents of that entire row or delete it altogether. You may need to be persistent (this is an Office application, after all). I had a user with this issue earlier today and I had to clear each cell one at a time and save the document before it would take effect. Once excel stops believing that there is something in the last rows, you'll be able to insert rows wherever you need. Answer 15 I ran into this same issue with VB. Here's what worked for me (from here): Dim mySelection As Excel.Range mySelection = ThisApplication.Selection() mySelection.EntireRow.Insert(Excel.XlInsertShiftDirection.xlShiftDown)

Answer 16 Hi, I have some what a strange requirement. Rather than reading the data from a sh eet or a range in excel, i need to get the information regarding named range an d based on that i need to filter the data further. For eg: if the range A1: C5 i s mapped to a named range as "Amount", i need to get the absolute range informa tion which is A1:C5 by passing the range "Amount". Is there any way of achieving this programmatically? Currently I am using oledb for reading the data. Thanks Jency Answer 17 It isnt that tough Simply create an object of workbook and worksheet Specifying the cells(rowindex, columnindex) you can easily bank out the values Amrit Answer 18 How can I reference columns in the excel spread sheet to use in an ORDER BY sta tement or in a WHERE clause? The code below is what I'm using to read from the Excel spreadsheet and it wor ks fine. I just need to sort the spread sheet. The spreadsheet doesn't have any headers DataTable dtExcel = objConn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGui d.Tables, newobject[] { null, null, null, "TABLE" }); string SpreadSheetName = "[" + dtExcel.Rows[0]["TABLE_NAME"].ToString() + "]"; DataSet dsExcel = newDataSet(); objCommand.CommandText = @"SELECT * FROM " + SpreadSheetName; Answer 19 The only problem here is that you're missing the ConvertToStringArray(myvalues); method. string[] ConvertToStringArray(System.Array values) { // create a new string array string[] theArray = newstring[values.Length]; // loop through the 2-D System.Array and populate the 1-D String Array for (int i = 1; i <= values.Length; i++)

{ if (values.GetValue(1, i) == null) theArray[i-1] = ""; else theArray[i-1] = (string)values.GetValue(1, i).ToString(); } return theArray; }

Answer 20 That's okay... you need to replace the null parameters with System.Reflection.Missing.Value in your "using" statement include System.Reflection. You might only need to add this statement once... I've had it work that way, but also have had to use it fo r all parameters... not sure what the difference is... I'm trying to get this fi gure out too. What I'm trying to do is pull out one row at a time from an excel sheet and get the file path from a hyperlink value. I know that there is a hyperlink object that with an address property like so, myFilePath = range.Hyperlinks(1).Address; but I keep getting an error on the hyperlink bit... really annoying me. Answer 21 Excel.Sheets sheets = theWorkbook.Worksheets; The next runtime error occurs when trying to run your code. System.InvalidCastException was unhandled Message="Unable to cast com object of type 'System.__ComObject' to class type 'Microsoft.Office.Interop.Excel.WorksheetClass'. COM components that enter the CLR and do not support IProvideClassInfo or that do not have any interop assembl y registered will be wrapped in the __ComObject type. Instances of this type can not be cast to any other class; however they can be cast to interfaces as long a s the underlying COM component supports QueryInterface calls for the IID of the interface." Source="Test1" StackTrace: at Test1.ExcelForm.Test(String filename) in D:\Projects\SSMSC\Test\Test1\ Form1.cs:line 30 at Test1.ExcelForm.button1_Click(Object sender, EventArgs e) in D:\Projec ts\SSMSC\Test\Test1\Form1.cs:line 43 at System.Windows.Forms.Control.OnClick(EventArgs e) at System.Windows.Forms.Button.OnClick(EventArgs e) at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent) at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button , Int32 clicks) at System.Windows.Forms.Control.WndProc(Message& m) at System.Windows.Forms.ButtonBase.WndProc(Message& m) at System.Windows.Forms.Button.WndProc(Message& m)

at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int3 2 msg, IntPtr wparam, IntPtr lparam) at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg) at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms .UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData) at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int 32 reason, ApplicationContext context) at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 re ason, ApplicationContext context) at System.Windows.Forms.Application.Run(Form mainForm) at Test1.Program.Main() in D:\Projects\SSMSC\Test\Test1\Program.cs:line 1 7 at System.AppDomain.nExecuteAssembly(Assembly assembly, String[] args) at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assembl ySecurity, String[] args) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() at System.Threading.ThreadHelper.ThreadStart_Context(Object state) at System.Threading.ExecutionContext.Run(ExecutionContext executionContex t, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart() Answer 22 when i 'm trying to read date from the cell, it's returning me a double value.. .can any one help me in this. Answer 23 There are also some .NET open source projects that offer excel read/write funct ionality: http://sourceforge.net/projects/nexcel/ - Reads from .xls ; doesn't require Exce l to be installedhttp://sourceforge.net/projects/koogra/ - Reads from .xls using COM automation ; requires Excel to be installedhttp://sourceforge.net/projects/ smartexcel/ - Writes binary Excel files ; doesn't require Excel to be installed Answer 24 Hi I need to insert a button into an excel sheet through C#, and then handle the c lick event using C# code, and not a macro. I tried using Excel.Button but could not handle the click event. I also tried us ing MSForms.CommandButton and could handle the click event if i added the button to an existing Excel sheet, but couldn't add the button through C# code. Could someone please help? //Using Excel.Button; Cant find Event Handler for Click event Excel.Buttons excelButtons; Excel.Button excelButton; excelButtons = (Excel.Buttons)excelSheet.Buttons(MIssing.Value); excelButton = excelButtons.Add(0, 0, 100, 20);

excelButton.Caption = "Hi"; //Using MSForms.CommandButton; Cant find a way to insert the button through C# c ode MSForms.CommandButton button; excelButton = button; btnClick = (MSForms.CommandButton)FindControl("btnClick"); btnClick.Click += newCommandButtonEvents_ClickEventHandler(btnClick_Click); object FindControl(string name) { returnFindControl(name, (Excel.Worksheet)excelBook.ActiveSheet); } objectFindControl(stringname, Excel.Worksheetsheet) { Excel.OLEObjecttheObject; try { theObject = (Excel.OLEObject)sheet.OLEObjects(name); returntheObject.Object; } catch { // Returns null if the control is not found. } returnnull; }

Answer 25 incase anyone wants to know how to do it in C# 2005 here is my code: in this example I wanted to read only certain cells so I did not need to use ar rays. DateTime effectiveDate; float currentRate; openFileDialog1.FileName = "*.xls"; if (openFileDialog1.ShowDialog() == DialogResult.OK) { Microsoft.Office.Interop.Excel.Application excelOBJ = new Microsoft.Office.Inter op.Excel.Application(); Microsoft.Office.Interop.Excel.Workbook theWorkbook = excelOBJ.Workbooks.Open(op enFileDialog1.FileName,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type. Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Mi ssing,Type.Missing,Type.Missing,Type.Missing);

Microsoft.Office.Interop.Excel.Worksheet sheets = (Microsoft.Office.Interop.Exce l.Worksheet) theWorkbook.Worksheets[1]; Range myRange = (Range) sheets.Cells[30,10]; currentRate = (float)Convert.ToDouble(myRange.Cells.Value2.ToString()); myRange = (Range)sheets.Cells[30, 2]; effectiveDate = Convert.ToDateTime(myRange.Cells.get_Value(Type.Missing).ToStrin g()); textBox1.AppendText(currentRate.ToString() + " " + effectiveDate.ToShortDateStri ng()); //not sure how many times to do this but 6 seems enough. I don't think excelOBJ == null ever happens even when it quits becasue a loop doesn't work. if (excelOBJ != null) { excelOBJ.Quit(); } if (excelOBJ != null) { excelOBJ.Quit(); } if (excelOBJ != null) { excelOBJ.Quit(); } if (excelOBJ != null) { excelOBJ.Quit(); } if (excelOBJ != null) { excelOBJ.Quit(); }

if (excelOBJ != null) { excelOBJ.Quit(); } } I have noticed that there is no loner a range.cells.value. Answer 26 Below is the whole code required for reading the Excel file. void Read_Excel() { // Test.xls is in the C:\ string connectionString = "Provider=Microsoft.Jet.OleDb.4.0;Data Source=" + C:\T est.xls + ";"; connectionString += "Extended Properties=Excel 8.0;"; // always read from the sheet1. OleDbCommand myCommand = newOleDbCommand("Select * from [Sheet1$];"); OleDbConnection myConnection = newOleDbConnection(connectionString); myConnection.Open(); myCommand.Connection = myConnection; OleDbDataReader myReader = myCommand.ExecuteReader(); while (myReader.Read()) { // it can read upto 5 columns means A to E. In your case if the requirement is d ifferent then change the loop limits a/c to it. for (int i = 0; i < 5; i++) { Response.Write(myReader.ToString() + " "); } Response.Write("<br>"); }

myConnection.Close(); } Answer 27 Very helpful info, thanks guys! Ke Answer 28 Did you find a solution to the following problem: when i 'm trying to read date from the cell, it's returning me a double value.. .can any one help me in this. Thanks Answer 29 I had similar problems few months ago, and I gave up from Excel... I would recommend you to use ExcelLite component, it has a free version with som e size limitations. It is much faster, and very easy to use... And client doesn' t need to have Office installed... You can download this component on: http://www.gemboxsoftware.com/ Answer 30 Hello, I opened the worksheet but couldn't read the values in cells as integer. It re quires explicit conversion can I tried convert.toint32 but still error occurs. code is:-> //definition of worksheet is Excel.Worksheet worksheet = (Excel.Worksheet)sheets.get_Item(1); int stemp = Convert.ToInt32 ( worksheet.Cells[1, 1]); Regards Harshal Answer 31 Hi, did you find out a way to dynamically insert a button in excel and get your c# method to be called when the button is clicked? Answer 32

Hello, I will refer here only the Web Applications. It is not possible to perform file I / O operations at Web Applications. Although you can read Excel files on .csv / .txt format. You can find an example on my site: http://www.wwv-it.com/WebServicesNet/ServicesNet.aspx, category Data conversions ,

Service "Convert Excel / Text files to data Sets / XML files / database tables ". I would be glad if you could help with this example. Do not hesitate to contact me if you need more information or code. Regards Einstein

Answer 33 j Answer 34 so Answer 35 so Answer 36 Dear fellows I have problem about which i donot from where i can get help. What is Working: I have made a ASP.NET (C#) application that is reading Data from excel (cell b

cell). That is working fine and i can check it in browser. Problem: Now using this code i made a web part in C# and i want to show it in SharPoint S erver 2007 site page. Now that is not working , thats mean not showing the web part on the page. And when i comment the excel ralated code in web part coding and check it at Sha rePoint server, web part works. I donot know what to do, Please Help Piece of code is: Excel.Application app = new Excel.Application(); Excel.Workbook wbook = null; Excel.Worksheet wsheet = null; Excel.Range range = null; app.Visible = false; Thread.CurrentThread.CurrentCulture = newCultureInfo("en-US"); string filepath = inputFile1.Value.ToString(); if (filepath != "") { wbook = app.Workbooks.Open(filepath, Missing.Value, Missing.Value, Missing.Value , Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value); string currentSheet = "Sheet1"; wsheet = (Excel.Worksheet)wbook.Worksheets.get_Item(currentSheet); range = wsheet.get_Range("B6", "H20"); System.Array myvalues = (System.Array)range.Cells.Value2; valueArray = ConvertToStringArray(myvalues);

if (app != null) { app.Workbooks.Close(); app.Quit(); } app = null; wsheet = null; range = null; Answer 37 Hi. To use this I need to add the microsoft Excel refrence to the project, right? The thing is I dont have microsoft offince on my computer. I use open office whi ch is kind of the same thing. But the problem is that I dont have that refrence in the com that when I want to add the refrence to my project. Is there any oth er way to do this or anywhere I can get that reference thing? thx Answer 38 Does anybody know to figure out what range of data was used for a chart object?

I like this bit of code posted earlier because it is easy to use: Range myRange = (Range) sheets.Cells[30,10]; currentRate = (float)Convert.ToDouble(myRange.Cells.Value2.ToString()); myRange = (Range)sheets.Cells[30, 2];

So, my plan is to figure out which cells were used to create a particular chart - i.e. which cells are the x-axis and which cells are the y-axis. Then just loo p through and grab the values to an array.

Any thought would be great...

Answer 39 learning Answer 40 I cannot find the function ConvertToStringArray. What dll do I need to include in my project to be able to use this function?

Answer 41 This is not ready made function, you have to write it yourself, here i can give u example, you can ajust the lengths acooring to your need, string[] ConvertToStringArray(System.Array values) { // create a new string array string[] theArray = newstring[values.Length]; int position = 0; // loop through the 2-D System.Array and populate the 1-D String Array for (int i = 1; i <16; i++) { for (int j = 1; j < 8; j++) { if (values.GetValue(i, j) == null) theArray[position++] = ""; else { theArray[position++] = (string)values.GetValue(i, j).ToString(); } } } return theArray; }

Cheerz Answer 42 i just asking How u open a excel sheet(Macro enable) in Moss site by button cli ck on Infopath form. Answer 43 Can u suggest how i open this excel sheet by Published infopath form.in moss220 7. and where i Save my excel sheet as it's macro enable so not published in moss. but i upload this excel sheet. in waiting ur reply./// Ankit jain......!! Answer 44 you can use OLED connection to do this http://csharp.net-informations.com/excel/csharp-excel-oledb-insert.htm bla. Answer 45 hI, I tried using this codebut the Response is undefined i tired some ways but coul d not find an answer. Somebody, help me.. Regards, Kishan K Answer 46 Read and write excel using C# Hope this helps Answer 47 hi, I have an issue while uploading the excel sheet from the Asp.Net Upload Contro l. Here is my scenario.

1) I am using my Asp.Net Upload Control to read the excel sheet data and work sheet names in the Uploaded Spreadsheet. 2)I am creating the folder in the local machine and saving the uploaded file i n Submit button. 3)Then I am reading the data of Excel Spreadsheet from the saved file in local machine using OledbConnection class in C#. I dont want to save the Uploaded file in the local machine and read it. Is there any possibility to read the Uploaded Excel File without saving it in L ocal Machine using Upload file control. Note : According to my requirement we can t use the Excel object from office.Excel .Interop dll s. We should implement with the help of OledbConnection class only. I am trying this from past 1week but no solution. Can anybody please help me re garding this problem. Thanks, Rajkamal.V rajkamal29 Answer 48 find the following link. http://csharp.net-informations.com/excel/csharp-excel-oledb.htm http://csharp.net-informations.com/excel/csharp-excel-tutorial.htm suzett. Answer 49 and if i want to open a xls that is allocated in a sharepoint site?? wich code i shoul use?? THANK YOU Answer 50 Hi, you could use GemBox .NET spreadsheet component to read Excel file . It supports import/export Excel to DataTable within just one method call, and t hen it is trivial to update database with ADO.NET. Answer 51 Is the get_Item not 1 based? I think I read somewhere that it is. Later Brian Answer 52 i was able to read the excel file using ole db reader. the question is want to read the first excel sheet no matter what its name is.

..as in if there are 3 sheets in my excel file...sheet1 ,sheet 2,sheet 3....i always want to read sheet 1 or if sheets name is a,b,c i always to read sheet a.is there a way to read this by default when the program loads ??? i m able to retrieve table names from the excel sheet but the sheet array ret urns 2 entries for each excel table. and everytime if i hard code the arrays .. i realize that it returns other tables index . how do i do this!! help !!! Answer 53 @Vital Parsley : you answer simple code sample generic excel reader , no matter how many sheets you want t o parse simple coding with simple life :D using System.Data.OleDb; using Excel = Microsoft.Office.Interop.Excel ; public static string ParseFile(string SourceLocation, string Desitnation, s tring FileName) { OleDbConnection _con = new OleDbConnection("Provider=Microsoft.ACE .OLEDB.12.0;Data Source="+SourceLocation+FileName+";Extended Properties=Excel 1 2.0"); try { _con.Open(); System.Data.DataTable _tab = new System.Data.DataTable(); System.Data.DataTable _SheetTable = new System.Data.DataTable( ); _SheetTable = _con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null); for (int Sheet = 0; Sheet < _SheetTable.Rows.Count; Sheet++) { OleDbCommand _com = new OleDbCommand("SELECT * FROM [" + _SheetTable.Rows[Sheet][2].ToString() + "]", _con); OleDbDataAdapter _dap = new OleDbDataAdapter(_com); _dap.Fill(_tab); string _Meesage = string.Empty; for (int x = 0; x < _tab.Rows.Count; x++) { for (int y = 0; y < _tab.Columns.Count; y++) { _Meesage += _tab.Rows[x][y].ToString() + ","; } _Meesage += "\r\n"; } string _FileName = _SheetTable.Rows[Sheet][2].ToString();

_FileName = _FileName.Replace("$", ""); _log.SuccessLoggingFileExcel(_FileName, _Meesage, Desitnat ion); } // _log.SuccessLogging("UFL", "Mesage from the Success Logging From the user"); return "Successessfully Parsed"; } catch (Exception ex) { Logging _lo = new Logging(); _log.LogErrorLog("Exception", ex); } } Hope this may help. Make life easy :)

Answer 54 Thanx for ur help. theres another problem i m facing with my application. i have 5 columns in my excel file out of which 2 are date columns.User enters d ate in these columns.In my application i m trying to upload files i got from my client. whats happening is when i keep the excel file open and try to upload the file t he date time columns are treated as some numbers (e.g 39044) instead of showing them as date.(this is as seen in the datatable i use to get excel data.i used a breakpoint to see this data).But if i upload the same file with excel file close d i can see the date column as dates in the datatable ! ! ! Why is this ? So, to find a solution i right clicked on the cell in excel and chose cell forma ts,in the general tab the date is shown as a number(e.g 39044 ) and not a date . in some of the other files i received from my client i saw the date as date (e.g 15/12/2009) and these files were uploaded into the datatable as dates even if t he excel file is closed or open. What exactly is the problem and solution to this ? Answer 55 YOR CODE HERE DOESNT WORK IF MY FILE SHEET NAME HERE HAS $ _FileName = _FileName.Replace("$", ""); Answer 56 IN IT.

WAT CULD BE DONE IS GET THE LAST INDEX POSITION OF $ AND USING SUBSTRING TO GET STRING BEFORE THAT INDEX POSITION ONE CAN GET THE TABLE NAME. Answer 57 Here's what finally worked for me:

object misValue = System.Reflection.Missing.Value; Excel.Application xlApp = new Excel.ApplicationClass(); Excel.Workbook xlWorkBook = xlApp.Workbooks.Open(path, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue); Excel.Worksheet worksheetOriginal = (Excel.Worksheet)xlWorkBook .Worksheets.get_Item(1); Excel.Range range = worksheetOriginal.get_Range("A1", "O50"); System.Array myvalues = (System.Array)range.Cells.Value2;

Carlos A Merighe. Answer 58 Thanks Farooqi , its works in my case.

Answer 59 thanks..it worked fine for me. Answer 60 Also check this link for help: http://prasanjitmandal.blogspot.com/2008/06/read-contents-of-excel-file-20032007 .html Answer 61 I use a best tool for creating an excel Spreadsheet with C#, it can reading a nd writing to excel 2007 or excel 2010 from c#. Spire.XLS Answer 62 ExcelObj is never declared anywhere. I think you need this line before ExcelObj can be used: Excel.Application ExcelObj = new Excel.Application(); Answer 63

using excel = Microsoft.Office.Interop.Excel; private void readExcel() { //Open file Dialog OpenFileDialog openFileDialog1 = new OpenFileDialog(); //filter file dialog hanya bisa buka file excel(xls) openFileDialog1.Filter = "Microsoft Excell Document|*.xls"; openFileDialog1.Title = "Select Document"; if (openFileDialog1.ShowDialog() == DialogResult.OK) {

//Method input data ke grid bool confirm = false;

if (AskExistingDataWillBeOverrided() == DialogResult.Yes) confirm = true; else confirm = false; if (confirm) { #region Import data ke Excel Excel.Application _excelApp = new Excel.Application();

Excel.Workbook workBook = _excelApp.Workbooks.Open(openF ileDialog1.FileName, Type.Missing, Type.Missing, Type.Missing, Type.Missi ng, Type.Missing, Type.Missing, Type.Missing, Type.Missi ng,

Type.Missing, Type.Missing, Type.Missing, Type.Missi ng, Type.Missing, Type.Missing); int numSheets = workBook.Sheets.Count; // // Iterate through the sheets. They are indexed starting at 1. // for (int sheetNum = 1; sheetNum < numSheets + 1; sheetNu m++) { Excel.Worksheet sheet = (Excel.Worksheet)workBook.Sh eets[sheetNum]; Excel.Range excelRange = sheet.UsedRange; object[,] valueArray = (object[,])excelRange.get_Val ue( Excel.XlRangeValueDataType.xlRangeValueDefault); for (int L = 3; L <= excelRange.Rows.Count; L++) { //Print valueArray[L,1]; //Print valueArray[L,2]; } //Or Another Method with valueArray Object like "Pro cessObjects(valueArray);" } workBook.Close(false, openFileDialog1.FileName, null); Marshal.ReleaseComObject(workBook); } } }

you can use it for reading an excel workbook with many sheet. Answer 64 I use VS2008 and build error: namespace "Excel" could not be found. And then I add "Microsoft.Office.Interop.Excel;" but error. Please help me! Related Answers: Reading Excel file from ShaPoint Update field... Reading from Excel and Writing to Excel Reading from Excel and Writing to Excel How to read excel file in document library an... in VS Express 2008 (Excel.Interop) Excel file... Reading Excel spreadsheet objects in a Word D... reading from Excel worksheet using OLEDB Problem while reading values from excel into ... How To Read Excel file in Visual Stdio 2008 Using OleDb to read Excel 2007 xls file - con... Read Excel File using OleDb "Unable to read file" error while opening Exc... Reading Excel files from 64-bit ASP.Net app Reading an excel file Reading data from Excel 2007 Read and update excel file row by row Read SPList using Excel Services Reading in jumbled Excel spreadsheets into Ac... Reading data using an Addin from Microsoft Ex... How to read excel file using javascript

Tagged: reading excel c# microsoft technologies sql server visual studio sha repoint sharepoint 2010 wpf wwf c# programming xml wcf vb.net wi ndows os c++ programming biztalk server .net framework azure ms office

<< Previous

Next >>

Microsoft | Windows | Visual Studio | Follow us on Twitter xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx with this Excel C# component you can easily export DataGridView to Excel, if Da taGridView is databound to BindingSource / DataSet / DataTable using this code: // Get DataTable that is data bound to DataGridView. var bindingSource = (BindingSource)dataGridView.DataSource; var dataView = (DataView)bindingSource.List; var dataTable = dataView.Table; // Create new Excel file. var excelFile = new ExcelFile(); // Add new worksheet and insert DataTable into it. excelFile.Worksheets.Add(dataTable.TableName).InsertDataTable(dataTable, "A1", t

rue); // Save Excel file to XLS format. excelFile.SaveXls(dataTable.TableName + ".xls"); xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxx you can export DataSet to Excel file, existing or new, with this Excel C# comp onent. Here is a C# code that shows how to do it: // Create new Excel file. var excelFile = new ExcelFile(); // Foreach DataTable, add new worksheet and insert data from DataTable into it. foreach (DataTable dataTable in dataSet.Tables) excelFile.Worksheets.Add(dataTable.TableName).InsertDataTable(dataTable, 0, 0, true); // Save Excel file to XLS format. excelFile.SaveXls(dataSet.DataSetName + ".xls"); xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

You might also like