Read Excel file data using C#
Question:
How to read Excel file data using C#? I've tried opening the file and copying it to the clipboard but not sure how to proceed.
Answer:
Using C# to read Excel file data, you can consider the following methods:
1. Create Excel object:
<code class="language-csharp">Excel.ApplicationClass ExcelObj = new Excel.ApplicationClass(); ExcelObj.Visible = false;</code>
2. Open workbook and worksheet:
<code class="language-csharp">Excel.Workbook theWorkbook = ExcelObj.Workbooks.Open(s.Text, 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, false, false); Excel.Worksheet worksheet = (Excel.Worksheet)theWorkbook.Worksheets.get_Item(count);</code>
3. Access cells as named ranges:
<code class="language-csharp">Excel.Range range = sheet.get_Range("A1", Missing.Value);</code>
4. Get cell value:
<code class="language-csharp">range.Text // 返回用户可见文本 range.Value2 // 返回Excel中存储的实际值</code>
5. Iterate cells:
<code class="language-csharp">Excel.Range range1 = sheet.get_Range("A1:A5", Missing.Value); if (range1 != null) { foreach (Excel.Range r in range1) { string user = r.Text; string value = r.Value2; } }</code>
Clean up:
Remember to close and release Excel objects in the reverse order of creation so they are disposed of correctly.
Example:
<code class="language-csharp">using System; using ExcelTools = Ms.Office; using Excel = Microsoft.Office.Interop.Excel; public class ExcelReader { public static void ReadWorkbook(string fileName) { Excel.Application excel = null; Excel.Workbook wkb = null; try { excel = new Excel.Application(); wkb = ExcelTools.OfficeUtil.OpenBook(excel, fileName); Excel.Worksheet sheet = wkb.Sheets["Data"] as Excel.Worksheet; Excel.Range range = sheet.get_Range("A1", Missing.Value); string A1 = String.Empty; if (range != null) A1 = range.Text.ToString(); Console.WriteLine("A1单元格的值: {0}", A1); } catch (Exception ex) { // 在此处处理错误 } finally { ExcelTools.OfficeUtil.ReleaseRCM(wkb); ExcelTools.OfficeUtil.ReleaseRCM(excel); } } }</code>
Additional notes:
The above is the detailed content of How to Read Data from an Excel File Using C#?. For more information, please follow other related articles on the PHP Chinese website!