Top Banner
Hè hè, đồ án xong rồi, ăn chơi nhảy múa tạm thời thế đã, giờ mình post tiếp các kinh nghiệm khi làm đồ án mà dính tới Excel. - Mô tả: khi thực hiện load dữ liệu từ file Excel vào trong csdl thì: 1. Mình biết cấu trúc file Excel đó <- phải có mẫu để load 2. Với nhiều sheet trong một workbook thì phải làm sao chỉ ra được: vị trí hoặc tên sheet đó để truyền dữ liệu vào trong database - Mình biết 2 kiểu đọc tên cái Excel sheet trong một Workbook đó là: 1. Nếu có nhiều sheet mà biết vị trí của sheet đó thì đọc tên theo vị trí 2. Nếu có nhiều sheet mà muốn load hết một lượt thì mình phải đọc tên được tất cả các sheet có trong một workbook Ngôn ngữ: C#. - Cách thứ nhất, là cách đơn giản vì ta đã biết vị trí rồi nên ko có gì là khó cả: public string GetSheetName(string FileName, int index) { string name = ""; ComExcel.Application ExcelApp = new ComExcel.Application(); ComExcel.Workbook ExcelBook = ExcelApp.Workbooks.Open(FileName, 0, false, 5, "", "", false, ComExcel.XlPlatform.xlWindows, "", true, false, 0, true, false, false); ComExcel.Worksheet ExcelSheet = (ComExcel.Worksheet)ExcelBook.Worksheets[index]; name = ExcelSheet.Name.ToString(); ExcelApp.Quit();
33

Excel Trong c

Apr 21, 2015

Download

Documents

Hieu Tran
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Excel Trong c

Hè hè, đồ án xong rồi, ăn chơi nhảy múa tạm thời thế đã, giờ mình post tiếp các kinh nghiệm khi làm đồ án mà dính tới Excel.

- Mô tả: khi thực hiện load dữ liệu từ file Excel vào trong csdl thì:

1. Mình biết cấu trúc file Excel đó <- phải có mẫu để load2. Với nhiều sheet trong một workbook thì phải làm sao chỉ ra được: vị trí hoặc tên sheet đó để truyền dữ liệu vào trong database

- Mình biết 2 kiểu đọc tên cái Excel sheet trong một Workbook đó là:

1. Nếu có nhiều sheet mà biết vị trí của sheet đó thì đọc tên theo vị trí2. Nếu có nhiều sheet mà muốn load hết một lượt thì mình phải đọc tên được tất cả các sheet có trong một workbook

Ngôn ngữ: C#.

- Cách thứ nhất, là cách đơn giản vì ta đã biết vị trí rồi nên ko có gì là khó cả:

public string GetSheetName(string FileName, int index){string name = "";ComExcel.Application ExcelApp = new ComExcel.Application();ComExcel.Workbook ExcelBook = ExcelApp.Workbooks.Open(FileName, 0, false, 5, "", "", false, ComExcel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);ComExcel.Worksheet ExcelSheet = (ComExcel.Worksheet)ExcelBook.Worksheets[index];name = ExcelSheet.Name.ToString();ExcelApp.Quit();

//Đóng ứng dụngSystem.Runtime.InteropServices.Marshal.ReleaseComO bject(ExcelBook);System.Runtime.InteropServices.Marshal.ReleaseComO bject(ExcelApp);

return name;}Cách lấy index khi đã biết tên thì ngược lại

public int GetSheetIndex(string FileName,string SheetName){int index = 0;ComExcel.Application ExcelApp = new ComExcel.Application();

Page 2: Excel Trong c

ComExcel.Workbook ExcelBook = ExcelApp.Workbooks.Open(FileName, 0, false, 5, "", "", false, ComExcel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);ComExcel.Sheets Sheets = ExcelApp.Worksheets;ComExcel.Worksheet ExcelSheet = (ComExcel.Worksheet)Sheets.get_Item(SheetName);

index = ExcelSheet.Index;ExcelApp.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComO bject(ExcelBook);System.Runtime.InteropServices.Marshal.ReleaseComO bject(ExcelApp);

return index;}- Cách thứ 2 đó là chúng ta lấy hết tất tần tật các Excel sheet ra, và mình làm là đưa các tên sheet rồi cho vào một cái combobox để người dùng có thể chọn dữ liệu mình để trong sheet đó rồi mới tiến hành cập nhật

public void AddSheetName2Combobox(string FileName, System.Windows.Forms.ComboBox cmb){OleDbConnection conn = new OleDbConnection();conn.ConnectionString = "provider=Microsoft.Jet.OLEDB.4.0;data source='" + FileName + "';Extended Properties=Excel 8.0;";conn.Open();try{DataTable dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

string[] excelSheetNames = new string[dt.Rows.Count];int i = 0;

foreach (DataRow row in dt.Rows){excelSheetNames[i] = row[2].ToString();i++;}

cmb.Items.Clear();

for (int s = 0; s < excelSheetNames.Length; s++){if (excelSheetNames[s].Substring(excelSheetNames[s].Length - 1, 1) != "_")cmb.Items.Add(excelSheetNames[s].ToString());}

Page 3: Excel Trong c

}catch { }finally {conn.Close();conn.Dispose();conn = null;}}+ Trong đây mình sử dụng chuỗi kết nối tới file Excel+ Chúng ta coi mỗi sheet là một bảng để lấy tên các bảng đó ra là ok+ Từ đây chúng ta thử nghiệm thì có thể lấy tổng số sheet trong file Excel

Đây là hình bài mình làm:[Only registered and activated users can see links]

+ Trong combobox là tên các sheet, chú ý là ko có dấu $ mới là tên thật.+ Lấy tổng số sheet

Page 4: Excel Trong c

Bài 1 thì gồm các hàm sử dụng với Excel

1. Chạy phần mềm Excel

Microsoft.Office.Interop.Excel.Application t = new Microsoft.Office.Interop.Excel.Application(); t.Visible = true;

2. Mở một file excel đã có, và cho biến x trỏ đến file excel này

Microsoft.Office.Interop.Excel.Workbook x; x = t.Workbooks.Open("E:\\DE_01.xls", 0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);

3. Tạo file excel mới, và cho biến x trỏ đến file excel này

Microsoft.Office.Interop.Excel.Workbook x; x = t.Workbooks.Add(true);

4. Cho một biến s trỏ đến một sheet của file excel x (đã tạo ở Lưu ý 2. hoặc 3.)

Microsoft.Office.Interop.Excel.Worksheet s; s = (Microsoft.Office.Interop.Excel.Worksheet) x.Worksheets[1];

5. Cho một biến r trỏ đến một ô hoặc một nhóm ô của sheet s

Microsoft.Office.Interop.Excel.Range r; r = s.get_Range("A1","A10");

6. Gán giá trị (chuỗi) cho một ô hoặc một nhóm ô (thuật ngữ excel gọi là range) trong sheet s

s.get_Range("A1", "A1").Value2 = "Hello everybody !";

hoặc

Microsoft.Office.Interop.Excel.Range r; r = s.get_Range("A1","A1"); r.Value2 = "Hello everybody !";

Page 5: Excel Trong c

7. Đọc giá trị (chuỗi) từ một ô trong sheet s

string m; m = s.get_Range("A1", "A1").Value2.ToString(); Console.WriteLine(m);

Nên kiểm tra xem nếu ô có dữ liệu thì mới đọc

string m = ""; if (s.get_Range("A1", "A1").Value2 != null) { m = s.get_Range("A1", "A1").Value2.ToString(); } Console.WriteLine(m);

8. Lưu (save) file excel x vào ổ đĩa

x.Save();

9. Lưu file excel x với một tên khác (Save as)

x.SaveAs("E:\\t.xls", Microsoft.Office.Interop.Excel.XlFileFormat.xlXMLSpreadsheet, false, false, false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, false, false, false, false, false);

10. Đóng file excel lại (mà không save)

x.Close(false,false,false);

11. Đóng ứng dụng:

ExcelApp.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(ExcelBook); System.Runtime.InteropServices.Marshal.ReleaseComObject(ExcelApp);

Đây mới là các hàm cơ bản...Về phần demo thì rảnh mình sẽ up lên phần đọc Excel này. Nếu bạn nào đã từng làm phần đọc Excel bằng VB6

Page 6: Excel Trong c

thì có thể nhận ra một số khác biệt như sau:

- Trong VB6 thì Cells có thể hiểu là giá trị trong một địa chỉ Sheets- Còn trong C# thì Range chứa các giá trị trong Sheets <- mình đã bị nhầm ở chỗ này....

So sánh 2:- Value2 của Range sẽ trả lại một giá trị đó là giá trị thực của cái cells đó- Text của Range sẽ trả lại giá trị hiển thị của cells đó

Ví dụ: Nếu về Text thì chả nói chuyện làm gì, vì nó hiển thị lên như kiểu nào mà chả giống nhauGiá trị đặc biệt chút: Datetime: khi gõ vào trong cells có thể thấy luôn: mình format thành dd/mm/yyyy14/04/2010 -> nhưng nó sẽ hiểu theo kiểu hiển thị của ngày giờ hệ thống đó là 4/14/2010 (mặc định kiểu US).Range.Text sẽ lấy cái 14/04/2010, còn Range.Value2 sẽ lấy giá trị 4/14/2010

Giới thiệu cái, rồi sẽ có phần chạy thử, kết nối bằng Oledb, lấy tên cách sheet, tuồn vào csdl, lôi ra windows Excel App

using System.Data.SqlClient; // để kết nối tới serverusing Microsoft.Office.Interop.Excel; // Sử dụng Excel

sự kiện Form_LOad sẽ thực hiện truyền dữ liệu ra Lưới Grid

Bấm vào đây để xem nội dung đầy đủ

public static SqlConnection conn = new SqlConnection("server=vinhnd-gw;uid=sa;pwd=sa;database=Northwind"); DataSet ds = new DataSet();

private void FormExcel_Load(object sender, EventArgs e) { SqlCommand sqlcmd = new SqlCommand("select * from Products", conn); SqlDataAdapter adp = new SqlDataAdapter(sqlcmd); adp.Fill(ds); Grid.DataSource = ds.Tables[0]; }

Khi click vào button

Page 7: Excel Trong c

Bấm vào đây để xem nội dung đầy đủ

private void CmdXuatFile_Click(object sender, EventArgs e) { Microsoft.Office.Interop.Excel.Application ExcelApp = new Microsoft.Office.Interop.Excel.Application(); Microsoft.Office.Interop.Excel.Workbook ExcelWork = ExcelApp.Workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet); Microsoft.Office.Interop.Excel.Worksheet ExcelSheet = (Microsoft.Office.Interop.Excel.Worksheet)ExcelWork.Sheets[1];

//Lấy tên các cột gắn vào dòng đầu tiên for (int i = 0; i < ds.Tables[0].Columns.Count - 1; i++) { ExcelSheet.Cells[1, i + 1] = ds.Tables[0].Columns[i].ColumnName; } //Chèn dữ liệu vào dòng thứ hai trở đi for (int i = 0; i < ds.Tables[0].Rows.Count - 1; i++) { for (int j = 0; j < ds.Tables[0].Columns.Count - 1; j++) { ExcelSheet.Cells[i + 2, j + 1] = ds.Tables[0].Rows[i][j].ToString(); } }

ExcelApp.Visible = true; }

Page 8: Excel Trong c

Đầu tiên, bạn viết một class DataTransformationService, class này sẽ thực hiện việc kết nối và lấy dữ liệu từ file excel:

Code:using System;using System.Data;using System.Data.OleDb;using System.Data.SqlClient;

namespace YourNamespace.Services{

/// <summary>/// Dịch vụ chuyển đổi dữ liệu/// </summary>public class DataTransformationService{

#region Private members

private string _provider = "Provider=Microsoft.Jet.OLEDB.4.0;";

private string _dataSourceString = "Data Source=";private string _dataSourceType = ";Extended

Properties=\"Excel 8.0;HDR=Yes;IMEX=1;ReadOnly:=false;UpdateLinks:=0\"";private string _fileName;

#endregion

public DataTransformationService(){

//// TODO: Add constructor logic here//

}

public string FileName{

get{ return _fileName; }set{ _fileName = value; }

}

public string ConnectionString{

get{

if(FileName == "") throw new NoNullAllowedException("File name must be required");

return _provider + _dataSourceString + FileName + _dataSourceType;

}}

/// <summary>

Page 9: Excel Trong c

/// Trả về các bảng(table)/sheet trong file DataSource/// </summary>/// <returns></returns>public DataTable GetTableNames(){

DataTable dtSheets = null;

using (OleDbConnection oledbConn = new OleDbConnection(ConnectionString))

{try{

oledbConn.Open();

//Trả về các sheet có trong file excel

dtSheets = oledbConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[]{null, null, null, "TABLE"});

}catch(Exception exc){

throw new Exception(exc.Message);}finally{

if(oledbConn != null)oledbConn.Close();

}}

return dtSheets;}

public DataSet GetDataImport(string tableName){

DataSet dsDataImport = new DataSet();bool isValid = false;

foreach(DataRow r in GetTableNames().Rows){

if(r[2].ToString() == tableName){

isValid = true;break;

}}

if(!isValid){

throw new Exception("Tên Table/Sheet không tồn tại trong file.");

}

string selectCommand = "select * from [" + tableName + "]";

Page 10: Excel Trong c

using (OleDbConnection oledbConn = new OleDbConnection(ConnectionString))

{try{

oledbConn.Open();

//Mở dữ liệu trong sheet được chọn và đổ vào DataSet

OleDbDataAdapter oleDataAdapter = new OleDbDataAdapter(selectCommand, oledbConn);

oleDataAdapter.Fill(dsDataImport);dsDataImport.Tables[0].TableName

= "CoDong";oleDataAdapter.Dispose();

}catch(Exception exc){

throw new Exception(exc.Message);}finally{

if(oledbConn != null)oledbConn.Close();

}}

return dsDataImport;}

}}

Link: http://www.ddth.com/showthread.php/363860-Help-%C4%91%E1%BB%8Dc-file-Excel-b%E1%BA%B1ng-C#ixzz1qbwy3IhWTiếp đến, bạn tạo một class xử lý dữ liệu của bạn. Ví dụ xử lý dữ liệu nhân viên:

Code:using System;using System.Data;using System.Data.SqlClient;using System.Data.OleDb;using Microsoft.ApplicationBlocks.Data;

namespace YourNamespace.Data{

public class SqlDataProvider{

//Các methods khác....//.....

//Phương thức import dữ liệu Nhân viênpublic bool ImportNhanViens(DataSet dsDataImport, ref string errorMessage)

{

Page 11: Excel Trong c

if(dsDataImport == null || dsDataImport.Tables.Count == 0) return false;

errorMessage = "";

SqlConnection conn = new SqlConnection(ConnectionString);

DataSet dsNhanVien = SqlHelper.ExecuteDataset(ConnectionString, CommandType.Text, "Select top 0 MaNhanVien, TenNhanVien, CMND, NgayCap, NoiCap, DiaChi, DienThoai from NhanVien");

dsCoDong.Tables[0].TableName = "NhanVien";

foreach(DataRow r in dsDataImport.Tables[0].Rows){

DataRow newRow = dsNhanVien.Tables[0].NewRow();

newRow["MaNhanVien"] = r[0].ToString();

newRow["TenNhanVien"] = r[1].ToString();

newRow["CMND"] = GetNull(r[2]); //CMND

newRow["NgayCap"] = GetNull(r[3]); //NgayCap

newRow["NoiCap"] = GetNull(r[4]); //NoiCap

newRow["DiaChi"] = GetNull(r[5]); //DiaChi

newRow["DienThoai"] = GetNull(r[6]); //DienThoai

dsNhanVien.Tables[0].Rows.Add(newRow);}

if(conn.State == ConnectionState.Closed)conn.Open();

SqlTransaction tran = conn.BeginTransaction();

SqlCommand cmdInsert = SqlHelper.CreateCommand(conn, "spNhanVien_Add", "MaNhanVien", "TenNhanVien", "CMND", "NgayCap", "NoiCap", "DiaChi", "DienThoai");

cmdInsert.Transaction = tran;SqlCommand cmdDelete =

SqlHelper.CreateCommand(conn, "spNhanVien_Delete", "MaNhanVien");cmdDelete.Transaction = tran;SqlCommand cmdUpdate =

SqlHelper.CreateCommand(conn, "spNhanVien_Update", "MaNhanVien", "TenNhanVien", "CMND", "NgayCap", "NoiCap", "DiaChi", "DienThoai");

cmdUpdate.Transaction = tran;

try{

SqlHelper.UpdateDataset(cmdInsert, cmdDelete, cmdUpdate, dsNhanVien, "NhanVien");

tran.Commit();

Page 12: Excel Trong c

return true;}catch(Exception exc){

errorMessage = exc.Message;tran.Rollback();return false;

}finally{

if(conn != null)conn.Close();

}}

}}

Link: http://www.ddth.com/showthread.php/363860-Help-%C4%91%E1%BB%8Dc-file-Excel-b%E1%BA%B1ng-C#ixzz1qbx3O4g9Bước tiếp theo, tạo class NhanVienController, đây là class trong tầng điều khiển:

Code:using System;using System.Collections;using System.Data;using YourNamespace.Data;

namespace YourNamespace.Entities.NhanVien{public class CoDongController

{#region Private static members

private static SqlDataProvider nhanvienDataProvider = new SqlDataProvider();

#endregion

// Các phương thức khác.....

public static bool ImportNhanViens(DataSet dsDataImport, ref string errorMessage)

{return

nhanvienDataProvider.ImportNhanViens(dsDataImport, ref errorMessage);}

}

}

Link: http://www.ddth.com/showthread.php/363860-Help-%C4%91%E1%BB%8Dc-file-Excel-b%E1%BA%B1ng-C#ixzz1qbx7HLoqBước cuối cùng là bạn thiết kế form, gồm có:1 TextBox txtFileName chứa đường dẫn tới file excel

Page 13: Excel Trong c

1 Button cmdBrowse [...] để mở hộp OpenFileDialog1 ComboBox cboTables chứa danh sách các sheet có trong file excel1 Button cmdPreview1 DataGrid dgData để hiển thị dữ liệu trong sheet được chọn.1 Button cmdImport để thực thi việc import dữ liệu vào database.

Code:#region Private members

private bool _fileNameChanged = false;private YourNamespace.Services.DataTransformationService

dts = new YourNamespace.Services.DataTransformationService();

#endregion

#region Private methods

private void FillSheetNames(){

dts.FileName = txtDataSource.Text;if(dts.FileName != ""){

System.Data.DataTable dt = dts.GetTableNames();

cboTables.DataSource = dt;cboTables.DisplayMember =

dt.Columns["TABLE_NAME"].ColumnName;cboTables.ValueMember =

dt.Columns["TABLE_NAME"].ColumnName;}

_fileNameChanged = false;}

private void LoadData(DataTable dtData){

if(DataSource != null)dgData.DataSource = dtData.DefaultView;

}

#endregion

private void cmdBrowse_ButtonClick(object sender, System.EventArgs e){

OpenFileDialog dlg = new OpenFileDialog();dlg.Filter = "Excel Files|*.xls";if(dlg.ShowDialog() == DialogResult.OK) {

txtFileName.Text = dlg.FileName;}

}

private void txtFileName_TextChanged(object sender, System.EventArgs e){

_fileNameChanged = true;

Page 14: Excel Trong c

FillSheetNames();}

private void btnPreview_Click(object sender, System.EventArgs e){

System.Data.DataSet ds = dts.GetDataImport(cboTables.Text);

LoadData(ds.Tables[0]);}

private void btnImport_Click(object sender, System.EventArgs e){

try {if(cboTables.Items.Count>0)

{string errorMessage = "";System.Data.DataSet dsNhanVien =

dts.GetDataImport(cboTables.Text);

if(NhanVienController.ImportNhanViens(dsNhanVien, ref errorMessage))

{MessageBox.Show("Quá trình

Import đã hoàn tất thành công!", "Import is Successfully");this.Close();

}else{

MessageBox.Show("Quá trình Import xảy ra lỗi khi Import dữ liệu!\n\n" + errorMessage, "Error Import Data", MessageBoxButtons.OK, MessageBoxIcon.Error);

}}

catch(Exception exc){}

}}

Link: http://www.ddth.com/showthread.php/363860-Help-%C4%91%E1%BB%8Dc-file-Excel-b%E1%BA%B1ng-C#ixzz1qbxDx2L6

Imports Excel = Microsoft.Office.Interop.ExcelPublic Class Form2    Public xlApp As Excel.Application    Public xlWorkBook As Excel.Workbook    Public xlWorkSheet As Excel.Worksheet

Page 15: Excel Trong c

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click        OpenFileDialog1.Filter = "Excel (*.xls;*.xlsx)|*.xls;*.xlsx"        OpenFileDialog1.ShowDialog()

        'Lấy Path từ OpenFileDialog1 nhét vào Textbox        TextBox1.Text = OpenFileDialog1.FileName

        'Mở Excel Application        xlApp = New Excel.ApplicationClass

        'Mở File Excel đã chọn        xlWorkBook = xlApp.Workbooks.Open(TextBox1.Text)

        'Lấy tên tất cả các Sheet        For Each xlWorkSheet In xlWorkBook.Worksheets            ComboBox1.Items.Add(xlWorkSheet.Name)        Next xlWorkSheet

        'Gán tên Sheet đầu tiên cho Combobox        ComboBox1.Text = (ComboBox1.Items(0).ToString())    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click

        'Lấy dữ liệu từ File        xlWorkSheet = xlWorkBook.Worksheets(ComboBox1.Text)

        'Duyệt các dòng có dữ liệu, bỏ qua dòng tiêu đề là dòng 1        Dim i, j As Integer        For i = 2 To xlWorkSheet.Rows.Count

            'Duyệt 5 cột đầu tiên            For j = 1 To 5                Dim s As String = xlWorkSheet.Cells(i, j).value                'Kiểm tra nếu ô đầu tiên của dòng là Null thì thoát khỏi For....Next                If s = Nothing Then                    Exit For                Else                    'Chỗ này muốn làm gì thì làm                End If            Next            Exit For        Next        MsgBox("xong rồi")

        'Close File and Excel Application        xlWorkBook.Close()        xlApp.Quit()    End SubEnd Class

Page 16: Excel Trong c

Getting Started

Pardon me for beating around the bush. Now let us jump in to the good part (coding). For this automation process we need to follow the below steps

1. Add a referrence to the Microsoft Excel object library COM component.2. Add the namespace Excel3. Instantiate the class Excel.ApplicationClass as below

Excel.Application xl=new Excel.ApplicationClass(); 4. To open an excel file,

Excel.Workbook wb=xl.Workbooks.Open(Environment.CurrentDirectory+"/SampleExcel.xls",0, false, 5, System.Reflection.Missing.Value, System.Reflection.Missing.Value, false, System.Reflection.Missing.Value, System.Reflection.Missing.Value,true, false, System.Reflection.Missing.Value, false, false, false);//Open the excel sheet

5. To read cell(s) in the worksheet,

Excel.Sheets xlsheets = wb.Sheets; //Get the sheets from workbookExcel.Worksheet excelWorksheet = (Excel.Worksheet)xlsheets[1]; //Select the first sheetExcel.Range excelCell = (Excel.Range)excelWorksheet.get_Range("B4:FZ4", Type.Missing); //Select a range of cellsExcel.Range excelCell2 = (Excel.Range)excelWorksheet.get_Range("A5:A5", Type.Missing); //Select a single cellConsole.WriteLine(excelCell2.Cells.Value2.ToString()); //Print the value of the cell for a single cell selectionSystem.Array myvalues = (System.Array)excelCell.Cells.Value2; //Assign it to an arraystring[] strArray = ConvertToStringArray(myvalues); //Convert array into String arrayforeach (string str in strArray)Console.WriteLine(" Text in Cell " + str); //Loop through the array to print the values in the cell

6. To save a value in a cell

excelCell2.Cells.Value2 = "SampleText"; //Assign a value to the cell

Page 17: Excel Trong c

wb.Save(); //Save the workbook7. Finally Quit the Excel Application

xl.Quit();

Conclusion

Excel is a great tool to work with. When it comes to automating, we need to consider many things. Always remember to quit the excel application in code before exiting. If not, the memory consumed by the excel application will not be freed up. 

Page 18: Excel Trong c

Đã có code java rồi giờ dùng C# xem nó có khác gì hok nhá!

Nhưng trước hết phải xem SMTP là cái gì đã. Giới thiệu qua chút về SMTP nhé:

- SMTP là một giao thức dùng nền văn bản và tương đối đơn giản. Trước khi một thông điệp được gửi, người ta có thể định vị một hoặc nhiều địa chỉ nhận cho thông điệp - những địa chỉ này thường được kiểm tra về sự tồn tại trung thực của chúng) . Việc kiểm thử một trình chủ SMTP là một việc tương đối dễ dàng, dùng chương trình ứng dụng "telnet" là một cách .

- SMTP dùng cổng 25 của giao thức TCP. Để xác định trình chủ SMTP của một tên miền nào đấy (domain name), người ta dùng một mẫu tin MX (Mail eXchange - Trao đổi thư) của DNS (Domain Name System - Hệ thống tên miền). Các bạn nên đọc thêm tư liệu về SMTP tại hai link này để hiểu thêm

http://tools.ietf.org/html/rfc1123

http://vi.wikipedia.org/wiki/SMTP

Mô hình :

Page 19: Excel Trong c

Giờ ta tạo Class MySMTP để xử lý quy trình như trong hình vẽ nhé:

- Trước hết là phải có mấy cái khái niệm như địa chỉ, đối tượng, thời gian gửi, rồi cổng nữa,.......... Tất cả khai báo ở đây:

Bấm vào đây để xem nội dung đầy đủ

private string Server; private string SenderName; private string SenderAddress; private string RCPName; private string RCPAddress; private string Subject; private string Body; private int TimeOut; private int Port; TcpClient SMTPTCPClient; NetworkStream SMTPNetworkStream; StreamReader SMTPStreamReader; StreamWriter SMTPStreamWriter; DateTime TimeOutCheck;

- Chú ý:+ Để tạo một connection ta cần sử dụng: TcpClient+ Để tạo một stream cho Network sử dụng NetworkStream+ Xử lý NetworkStream qua 2 cái Base trước đó: StreamReader và StreamWriter.+ DateTime: để quản lý connection , trường hợp bị TimeOut

+ Có các thành phần rồi giờ đơn giản thì ta tạo các Properties trước như đoạn code dưới

Page 20: Excel Trong c

--------- PROPERTIES--------------------

Bấm vào đây để xem nội dung đầy đủ

// Property: Server public string SMTPServer { get { return Server; } set { Server = value; } } // Property: SenderName public string SMTPSenderName { get { return SenderName; } set { SenderName = value; } } // Property: SenderAddress public string SMTPSenderAddress { get { return SenderAddress; } set { SenderAddress = value; } } // Property: RCPName public string SMTPRCPName { get { return RCPName; } set { RCPName = value; } } // Property: RCPAddress public string SMTPRCPAddress { get { return RCPAddress; } set { RCPAddress = value; } } // Property: Subject public string SMTPSubject { get { return Subject; } set { Subject = value; } } // Property: Body public string SMTPBody { get { return Body; } set { Body = value; } } // Property: TimeOut public int SMTPTimeOut { get { return TimeOut; } set { TimeOut = value; } } // Property: Port

Page 21: Excel Trong c

public int SMTPPort { get { return Port; } set { Port = value; } }

+ Với xử lý việc gửi mail thì có thể chỉ cần sử dụng 1 phương thức:a. Gửi Email đi : OnSendEmail() là đủNhưng khi send Email ta cần kiểm tra connection time out vì thế phải xác nhận response từ server thì mới có thể request và biết nên đóng connection cho hợp lý. Vì vậy thêm 1 phương thức nữa xử lý TimeOut

b. Xử lý Connection TimeOut: WaitForResponse()+ Xử lý gửi thông điệp đi thực sự rất đơn giản và không phức tạp.

Vậy là :

1. Khởi tạo kết nối, thất bại thì đóng2. Khởi tạo thành công, thu nhận thông điệp vào các stream3. Chào server, code = 220; đóng nếu thật bại4. Xử lý sender address: đóng nếu thất bại . code =2505. Xử lý người nhận : đóng nếu thất bại. code = 2506. Xử lý data:Thông tin Data của thông điệp gửi đi có 2 phần chính:-- Header Info --From:To:Subject:-- Message Info --Body:

Ngoài ra còn một số thông tin khác bổ sung cho Header như DateTime, Reply-To....

7. Gửi thông điệp , đóng nếu thất bại. Code = 3548. Kiểm tra thông điệp nếu được gửi thành công: code = 250. Đóng nếu thất bại

Chú ý: việc xử lý các bước đều thông qua viẹc xử lý connection time out.Vì xử lý thông điệp tới server có 2 kết quả, thành công hoặc thất bại nên 2 phương thức ta viết ở sử dụng kiểu Boolean (bool)

Ta bắt đầu tiến hành vào code thực dụng cho 2 phương thức:+ public void OnSendEmail()+ private void WaitForResponse(string Code) ( sử dụng private vì public thì ai dùng , có mỗi thằng OnSendEmail nó xài. Thêm vào đó Response code thì dùng kiểu String chứ không dùng Int vì tránh phải convert khi kiểm tra và so sánh từ stream. Thông điệp từ

Page 22: Excel Trong c

stream luôn là kiểu String).

Bấm vào đây để xem nội dung đầy đủ

using System;using System.Collections.Generic;using System.IO;using System.Net;using System.Net.Sockets;using System.Text;

namespace Network{ public class MySMTP { // Mail Properties private string Server; private string SenderName; private string SenderAddress; private string RCPName; private string RCPAddress; private string Subject; private string Body; private int TimeOut; private int Port; // Network Connector Properties TcpClient SMTPTCPClient; NetworkStream SMTPNetworkStream; StreamReader SMTPStreamReader; StreamWriter SMTPStreamWriter; DateTime TimeOutCheck;

// Constructor public MySMTP() { TimeOut = 60; // Set Connection Time Out around 1 minute Port = 25; // which is accessed through Telnet }

/* * PROPERTIES */ // Property: Server public string SMTPServer { get { return Server; } set { Server = value; } } // Property: SenderName public string SMTPSenderName { get { return SenderName; }

Page 23: Excel Trong c

set { SenderName = value; } } // Property: SenderAddress public string SMTPSenderAddress { get { return SenderAddress; } set { SenderAddress = value; } } // Property: RCPName public string SMTPRCPName { get { return RCPName; } set { RCPName = value; } } // Property: RCPAddress public string SMTPRCPAddress { get { return RCPAddress; } set { RCPAddress = value; } } // Property: Subject public string SMTPSubject { get { return Subject; } set { Subject = value; } } // Property: Body public string SMTPBody { get { return Body; } set { Body = value; } } // Property: TimeOut public int SMTPTimeOut { get { return TimeOut; } set { TimeOut = value; } } // Property: Port public int SMTPPort { get { return Port; } set { Port = value; } }

/* * METHOD */

// Send message through telnet connection public bool OnSendEmail() { // Initialization SMTPTCPClient = new TcpClient(); // Set up the connection try {

Page 24: Excel Trong c

SMTPTCPClient.Connect(Server, Port); } catch (Exception ex) { // if fail to connect to mail server Console.WriteLine("Error: " + ex.Message); return false; } // If succeed creating the connection // init all the streams SMTPNetworkStream = SMTPTCPClient.GetStream(); SMTPStreamReader = new StreamReader(SMTPNetworkStream); SMTPStreamWriter = new StreamWriter(SMTPNetworkStream);

// Need for server's response if (WaitForResponse("220")) { // Greet mail server SMTPStreamWriter.WriteLine("HELO: " + Server); // Clear the rest/garbage SMTPStreamWriter.Flush(); } else // if no response from server { // connection fails SMTPTCPClient.Close(); return false; }

// The next response for input sender address if (WaitForResponse("250")) { // write down the sender address SMTPStreamWriter.WriteLine("Mail From:" + SenderAddress); SMTPStreamWriter.Flush(); } else { // connection close otherwise SMTPTCPClient.Close(); return false; }

// Response for input RCP Address if (WaitForResponse("250")) { // write down the RCP address SMTPStreamWriter.WriteLine("RCPT TO:" + RCPAddress); SMTPStreamWriter.Flush(); } else { // close the connection otherwise SMTPTCPClient.Close(); return false; }

Page 25: Excel Trong c

// Response for data / body if (WaitForResponse("250")) { // request data SMTPStreamWriter.WriteLine("Data"); SMTPStreamWriter.Flush(); } else { // close connection otherwise SMTPTCPClient.Close(); return false; }

// Send the message if (WaitForResponse("354")) { // Get all message // NOTE: Each section should be ended up with a newline seperately string szData = ""; szData = "From:" + SenderName + Environment.NewLine; szData += "To:" + RCPName + Environment.NewLine; szData += "Subject:" + Subject + Environment.NewLine; szData += Body + Environment.NewLine + "." + Environment.NewLine;

// Send the message to network stream through stream writer SMTPStreamWriter.Write(szData); // clear the rest SMTPStreamWriter.Flush(); } else { // close the connection if fails SMTPTCPClient.Close(); return false; }

// Wait for the last success if (WaitForResponse("250")) { // close the connection safely SMTPTCPClient.Close(); return true; } else { // close the connection otherwise SMTPTCPClient.Close(); return false; } }

// WaitForResponse method manipulates the connection response.

Page 26: Excel Trong c

private bool WaitForResponse(string Code) { // Get the time at connecting moment TimeOutCheck = DateTime.Now; // Span the timer TimeSpan TimeSpanner = DateTime.Now - TimeOutCheck; // Loop until timeout exceeds while (TimeSpanner.Seconds < TimeOut) { if (SMTPNetworkStream.DataAvailable) { // If catch the incoming data, get it by lines string DataIn = SMTPStreamReader.ReadLine(); // Check for the sufficient response code if (DataIn.Substring(0, Code.Length).Equals(Code)) return true; } // Recalculate timeout TimeSpanner = DateTime.Now - TimeOutCheck; } // Return false if it fails return false; } }

public class Network { public static void Main() { // Create a SMTP Object MySMTP smtp = new MySMTP(); smtp.SMTPServer = "gsmtp163.google.com"; smtp.SMTPPort = 25; smtp.SMTPTimeOut = 60; smtp.SMTPSenderName = "Pete Houston"; smtp.SMTPSenderAddress = "[email protected]"; smtp.SMTPRCPName = "Pete Houston"; smtp.SMTPRCPAddress = "[email protected]"; smtp.SMTPSubject = "Testing for SMTP Class"; smtp.SMTPBody = "Hello Pete ! Message Sent Successfully !";

Console.WriteLine("Sending ... \n"); // Try to send email if (smtp.OnSendEmail()) { Console.WriteLine("OK !"); } else { Console.WriteLine("Failed !"); }

} }}

Page 27: Excel Trong c

Hết phần 1 rồi đấy! Nhưng vẫn còn nhiều cái thú vị nữa! Bữa say chiến tiếp. Anh em cho đóng góp đi đã!