The post Tạo và ghi Excel files trong C# sử dụng Open XML và closed XML appeared first on Tân Hồng IT.
]]>Đầu tiên, chúng ta tải thư viện ClosedXML miễn phí ở địa chỉ: https://www.nuget.org/packages/ClosedXML/
Bạn hãy tạo 1 dự án C# Console và nhúng thư viện này vào dự án vừa tạo.
Bạn tạo 1 Project Console App(.Net Framework)
Tiếp theo bạn chuột phải vào References và chọn tiếp vào Manage Nuger Packafes…
Sau đó bạn tìm kiếm với từ khóa Spire, nó sẽ sổ ra một list các thư viện, bạn hãy chọn thư viện ClosedXML như hình bên dưới để cài đặt.
Bạn tiếp tục nhấn Install và nhấn vào I Accept và chờ cho nó tự động cài đặt thư viện vào nhé!
Sau khi cài xong nếu bạn thấy trong References có những thư viện như hình bên dưới thì đã add thành công.
Ở đây đang chuyển đổi Dataset thành file Excel, nếu tập dữ liệu chứa nhiều DataTables, nó có thể được lặp vào cùng một Excel với các trang tính khác nhau. Dưới đây là code để kết nối Tạo Excel (.xlsx) và lưu vào đường dẫn chỉ định.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ClosedXML.Excel; using DocumentFormat.OpenXml.Spreadsheet; using System.Data; using Excel = Microsoft.Office.Interop.Excel; using System.Runtime.InteropServices; //su dung phong thuc ClosedXML de hoan thanh namespace ghifileexcel { class Program { static void Main(string[] args) { DataSet ds = new DataSet(); DataTable dt = new DataTable(); dt.Columns.Add("Name"); dt.Columns.Add("Country"); dt.Rows.Add("Venkatesh", "India"); dt.Rows.Add("Santhosh", "USA"); dt.Rows.Add("Venkat Sai", "Dubai"); dt.Rows.Add("Venkat Teja", "Pakistan"); ds.Tables.Add(dt); ExportDataSetToExcel(ds); } public static void ExportDataSetToExcel(DataSet ds) { string AppLocation = ""; AppLocation = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().CodeBase); AppLocation = AppLocation.Replace("D:\\HKIII\\1. BTCL\\tuan4_chuong2_3\\ghifileexcel/DataTable.xlsx", ""); string date = DateTime.Now.ToShortDateString(); date = date.Replace("/", "_"); //string filepath = AppLocation + "\\ExcelFiles\\" + "RECEIPTS_COMPARISON_" + date + ".xlsx"; string filepath = "D:\\HKIII\\1. BTCL\\tuan4_chuong2_3\\ghifileexcel/DataTable.xlsx"; using (XLWorkbook wb = new XLWorkbook()) { for (int i = 0; i < ds.Tables.Count; i++) { wb.Worksheets.Add(ds.Tables[i], ds.Tables[i].TableName); } wb.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center; wb.Style.Font.Bold = true; wb.SaveAs(filepath); } } } }
Tài liệu tham khảo:
Xem thêm:
CHÚC CÁC BẠN THÀNH CÔNG VÀ VUI VẺ
The post Tạo và ghi Excel files trong C# sử dụng Open XML và closed XML appeared first on Tân Hồng IT.
]]>The post Cách tạo và ghi file Word, PDF trong C# với thư viện Spire.Doc, Spire.PDF appeared first on Tân Hồng IT.
]]>Đầu tiên, chúng ta tải 2 thư viện Spire.Doc và Spire.PDF bản miễn phí ở địa chỉ: https://www.e-iceblue.com/Download/download-word-for-net-free.html và https://www.e-iceblue.com/Download/download-pdf-for-net-free.html.
Hoặc bạn tải về theo link google drive mình chuẩn bị sẵn Tại Đây
Bạn hãy tạo 1 dự án C# Console và nhúng thư viện này vào dự án vừa tạo.
Bạn tạo 1 Project Console App(.Net Framework)
Tiếp theo bạn chuột phải vào References và chọn tiếp vào Manage Nuger Packafes…
Sau đó bạn tìm kiếm với từ khóa Spire, nó sẽ sổ ra một list các thư viện, bạn hãy chọn thư viện Spire.Office (Sẽ bao gồm đọc tất cả các file office và cả pdf) hoặc chọn Spire.PDF và Spire.Doc.
Bạn tiếp tục nhấn Install và nhấn vào I Accept và chờ cho nó tự động cài đặt thư viện vào nhé!
Sau khi cài xong nếu bạn thấy trong References có những thư viện như hình bên dưới thì đã add thành công.
Giờ thì bắt đầu Code.
Ví dụ sau tạo 1 đoạn văn bản “Hello World!” in đậm canh giữa vào tập tin mới test.doc (hoặc test.pdf). Tập tin mới sẽ nằm ở thư mục Debug, bạn có thể tùy chỉnh đường dẫn tập tin tùy ý nếu muốn.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Spire.Doc; using Spire.Pdf; using Spire.Doc.Documents; using Spire.Doc.Fields; namespace TestProject { class Program { static void Main(string[] args) { // Tạo đối tượng tài liệu (Document) Document doc = new Document(); // Tạo đối tượng đoạn (Paragraph) Paragraph paragraph = doc.AddSection().AddParagraph(); // Tạo văn bản (TextRange) Spire.Doc.Fields.TextRange text = paragraph.AppendText("Hello World!"); //text.CharacterFormat.Italic = true; // in nghiêng //text.CharacterFormat.UnderlineStyle = UnderlineStyle.Single; // gạch chân text.CharacterFormat.Bold = true; // kiểu in đậm paragraph.Format.TextAlignment = TextAlignment.Center; // văn bản canh giữa paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center; // đoạn canh giữa //paragraph.Format.HorizontalAlignment = HorizontalAlignment.Left; // đoạn canh trái //paragraph.Format.HorizontalAlignment = HorizontalAlignment.Right; // đoạn canh phải // Lưu đối tượng tài liệu vào tập tin test.doc (nằm ở thư mục Debug của dự án) doc.SaveToFile("test.doc", Spire.Doc.FileFormat.Doc); // doc.SaveToFile("test.pdf", Spire.Doc.FileFormat.PDF); -- tạo PDF // đóng đối tượng doc.Close(); } } }
Nhìn lại code trên, tại dòng 21, khi tạo 1 đoạn mới chúng ta dùng đoạn mã Paragraph paragraph = doc.AddSection().AddParagraph();
Tuy nhiên để thêm 1 đoạn mới nữa bạn phải dùng hàm doc.Sections[0].AddParagraph(); như trong ví dụ sau đây.
// đoạn mới tên biến là paragraph2 Paragraph paragraph2 = doc.Sections[0].AddParagraph(); // tên văn bản mới là text2 Spire.Doc.Fields.TextRange text2 = paragraph2.AppendText("Nhập nội dung đoạn mới"); text2.CharacterFormat.FontSize = 18; text2.CharacterFormat.Bold = true;
Để canh Tab thì dùng paragraph2.Format.Tabs.AddTab(175).Justification = TabJustification.Right; với TabJustification.Right là Tab phải và 175 (float) là vị trí Tab, ngoài ra có có Tab trái ở vị trí 375 (Left) và Tab giữa (Centered) chưa được thêm vào.
Paragraph paragraph2 = doc.Sections[0].AddParagraph(); // Canh Tab phải vị trí 175 paragraph2.Format.Tabs.AddTab(175).Justification = TabJustification.Right; paragraph2.Format.Tabs.AddTab(375).Justification = TabJustification.Left; //paragraph2.Format.Tabs.AddTab(175).Justification = TabJustification.Centered; // Phải có \t để dịch đến Tab cần canh Spire.Doc.Fields.TextRange text2 = paragraph2.AppendText("\t Canh phải \t Canh trái");
Đầu tiên bạn phải thêm thư viện System.Drawing vào dự án (Add Reference), sau đó gọi 2 namespace ở trên đầu file code.
using Spire.Doc.Fields; using System.Drawing;
Tiếp theo tạo đối tượng Bitmap và DocPicture để thêm hình vào đối tượng Document.
// Tạo đối tượng hình ảnh DocPicture (using using Spire.Doc.Fields;) DocPicture picture = doc.Sections[0].Paragraphs[0].AppendPicture(b1); // Vị trí ảnh theo chiều dọc, ngang picture.HorizontalPosition = 50.0F; picture.VerticalPosition = 200.0F; // Kích thước ảnh picture.Width = 150; picture.Height = 100; // Kiểu chèn ảnh nổi trên văn bản picture.TextWrappingStyle = TextWrappingStyle.InFrontOfText;
Chúng ta dùng đối tượng Table để tạo bảng, trong đó tạo dòng tiêu đề trước và phần dữ liệu từng dòng sau.
// Dữ liệu mẫu List<string> list = new List<string> { "One", "True", "Three" }; // Tạo đối tượng bảng Table Spire.Doc.Table table = doc.Sections[0].AddTable(true); // Tạo cột String[] Header = { "STT", "Tên"}; // Số dòng và số cột cho bảng table.ResetCells(list.Count + 1, Header.Length); // Độ rộng bảng ở dòng 0 và 2 cột STT và Tên (tạo tiêu đề bảng) doc.Sections[0].Tables[0].Rows[0].Cells[0].Width = 200; doc.Sections[0].Tables[0].Rows[0].Cells[1].Width = 200; // Tạo dòng tiêu đề cho bảng (dòng 0) Spire.Doc.TableRow FRow = table.Rows[0]; FRow.IsHeader = true; FRow.Height = 23; for (int i = 0; i < Header.Length; i++) { // Định dạng cell Paragraph p = FRow.Cells[i].AddParagraph(); FRow.Cells[i].CellFormat.VerticalAlignment = VerticalAlignment.Middle; p.Format.HorizontalAlignment = HorizontalAlignment.Center; // Định dạng văn bản trong bảng Spire.Doc.Fields.TextRange TR = p.AppendText(Header[i]); TR.CharacterFormat.FontName = "Times New Roman"; TR.CharacterFormat.FontSize = 13; TR.CharacterFormat.Bold = true; } // Định dạng dữ liệu từng dòng (lấy từ list) for (int r = 0; r < list.Count; r++) { doc.Sections[0].Tables[0].Rows[r + 1].Cells[0].Width = 200; doc.Sections[0].Tables[0].Rows[r + 1].Cells[1].Width = 200; // Định dạng dòng thứ r + 1 (bỏ dòng đầu là tiêu đề) Spire.Doc.TableRow DataRow = table.Rows[r + 1]; DataRow.Height = 20; DataRow.Cells[0].CellFormat.VerticalAlignment = VerticalAlignment.Middle; Paragraph p1 = DataRow.Cells[0].AddParagraph(); Spire.Doc.Fields.TextRange TR1 = p1.AppendText((r + 1).ToString()); // STT p1.Format.HorizontalAlignment = HorizontalAlignment.Center; DataRow.Cells[1].CellFormat.VerticalAlignment = VerticalAlignment.Middle; Paragraph p2 = DataRow.Cells[1].AddParagraph(); Spire.Doc.Fields.TextRange TR2 = p2.AppendText(list[r].ToString()); // Tên p2.Format.HorizontalAlignment = HorizontalAlignment.Center; }
Tương tự như đoạn code mẫu bên trên. ở phần này mình có thay đổi một chút xíu đó là những gì cần ghi vào file word sẽ phải nhập từ màn hình Console. Các bạn có thể tham khảo.
using System.Drawing; using System; using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; using Spire.Doc.Formatting; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; //ghi text vao file word su dụng phương thức Spire namespace ghifileword { class Program { static void Main(string[] args) { Document doc = new Document(); Section sec = doc.AddSection(); Paragraph par = sec.AddParagraph(); TextBox textBox = par.AppendTextBox(180, 30); textBox.Format.VerticalOrigin = VerticalOrigin.Margin; textBox.Format.VerticalPosition = 100; textBox.Format.HorizontalOrigin = HorizontalOrigin.Margin; textBox.Format.HorizontalPosition = 50; textBox.Format.NoLine = true; CharacterFormat format = new CharacterFormat(doc); format.FontName = "Calibri"; format.FontSize = 15; format.Bold = true; Paragraph par1 = textBox.Body.AddParagraph(); string line = ""; Console.WriteLine("Nhap chu can ghi vao file word : "); line = Console.ReadLine(); par1.AppendText(line).ApplyCharacterFormat(format); doc.SaveToFile("D:/HKIII/1. BTCL/tuan4_chuong2_3/ghifileword/result.docx", FileFormat.Docx); doc.SaveToFile("D:/HKIII/1. BTCL/tuan4_chuong2_3/ghifileword/result.doc", FileFormat.Doc); } } }
Tài liệu tham khảo:
Xem thêm:
CHÚC CÁC BẠN THÀNH CÔNG VÀ VUI VẺ
The post Cách tạo và ghi file Word, PDF trong C# với thư viện Spire.Doc, Spire.PDF appeared first on Tân Hồng IT.
]]>The post Mở Đọc File Excel Trong C# Với Microsoft Office Interop Excel dll appeared first on Tân Hồng IT.
]]>Phương pháp này cũng sử dụng thư viện Interop giống bài viết trước. Đầu tiên, thêm tham chiếu vào Thư viện đối tượng Microsoft Excel XX.X , nằm trong tab COM của Trình quản lý tham chiếu. Mình đã đưa ra điều này bằng cách sử dụng bí danh của Excel.
using Excel = Microsoft.Office.Interop.Excel; //Microsoft Excel 14 object in references-> COM tab
Nếu các bạn cảm thấy khó khăn ở bước trên mình sẽ hướng dẫn chi tiết về bước trên cho các bạn tại đây.
Bạn bắt buộc phải tải DLL Microsoft.Office.Interop.Excel về máy mới có thể hoàn thành bài code này.
Đây là link cập nhật phiên bản mới nhất: Download Microsoft.Office.Interop.Excel.dll
Hoặc nếu link die thì các bạn cũng có thể Download Phiên bản 15.0.4569.1506
Tiếp theo Bạn tạo 1 Project Console App(.Net Framework)
Trong Solution Explorer , bấm chuột phải vào tên dự án của bạn và sau đó bấm Add Reference . Các Add Reference hộp thoại sẽ xuất hiện.
Trên trang Assemblies, click chọn Microsoft.Office.Interop.Excel trong danh sách Component Name . Và nhấn OK.
Sau khi đã làm những bước trên bạn có thể thêm tham chiếu vào thư viện được rồi.
using Excel = Microsoft.Office.Interop.Excel; using Word = Microsoft.Office.Interop.Word;
Tiếp theo, bạn sẽ cần tạo references cho từng đối tượng COM được truy cập. Mỗi references phải được lưu giữ để thoát khỏi ứng dụng một cách hiệu quả khi hoàn thành.
// Tạo đối tượng COM. Tạo một đối tượng COM cho mọi thứ được tham chiếu Excel.Application xlApp = new Excel.Application(); Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(@"sandbox_test.xlsx"); Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1]; Excel.Range xlRange = xlWorksheet.UsedRange;
Sau đó, bạn có thể đọc từ trang tính sheet, hãy nhớ rằng lập chỉ mục trong Excel không dựa trên 0. Điều này chỉ cần đọc các ô và in chúng trở lại giống như trong tệp.
//Lặp lại qua các hàng và cột và in ra bàn điều khiển khi nó xuất hiện trong tệp //excel is not zero based!! for (int i = 1; i <= rowCount; i++) { for (int j = 1; j <= colCount; j++) { //dòng mới if (j == 1) Console.Write("\r\n"); //ghi giá trị vào bàn điều khiển console if (xlRange.Cells[i, j] != null && xlRange.Cells[i, j].Value2 != null) Console.Write(xlRange.Cells[i, j].Value2.ToString() + "\t"); } }
Cuối cùng, các tham chiếu (references) đến bộ nhớ không được quản lý phải được xuất ra. Nếu điều này không được thực hiện đúng cách, thì sẽ có các quy trình kéo dài giữ quyền truy cập tập tin và ghi vào file Excel của bạn.
//cleanup GC.Collect(); GC.WaitForPendingFinalizers(); //quy tắc của việc phát hành các đối tượng com: //không bao giờ sử dụng hai dấu chấm, tất cả các đối tượng COM phải được tham chiếu và phát hành riêng lẻ // ví dụ: [somthing].[something].[something] ----> bad //xuất các đối tượng com để dừng hoàn toàn quá trình excel chạy trong nền Marshal.ReleaseComObject(xlRange); Marshal.ReleaseComObject(xlWorksheet); //đóng lại và xuất thông tin xlWorkbook.Close(); Marshal.ReleaseComObject(xlWorkbook); //thoát và xuất thông tin xlApp.Quit(); Marshal.ReleaseComObject(xlApp);
Full Code đầy đủ để đọc 1 file Excel trong C# :
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using Excel = Microsoft.Office.Interop.Excel; //microsoft Excel 14 object in references-> COM tab namespace Sandbox { public class Read_From_Excel { public static void getExcelFile() { //Create COM Objects. Create a COM object for everything that is referenced Excel.Application xlApp = new Excel.Application(); Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(@"C:\Users\E56626\Desktop\Teddy\VS2012\Sandbox\sandbox_test - Copy - Copy.xlsx"); Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1]; Excel.Range xlRange = xlWorksheet.UsedRange; int rowCount = xlRange.Rows.Count; int colCount = xlRange.Columns.Count; //iterate over the rows and columns and print to the console as it appears in the file //excel is not zero based!! for (int i = 1; i <= rowCount; i++) { for (int j = 1; j <= colCount; j++) { //new line if (j == 1) Console.Write("\r\n"); //write the value to the console if (xlRange.Cells[i, j] != null && xlRange.Cells[i, j].Value2 != null) Console.Write(xlRange.Cells[i, j].Value2.ToString() + "\t"); } } //cleanup GC.Collect(); GC.WaitForPendingFinalizers(); //rule of thumb for releasing com objects: // never use two dots, all COM objects must be referenced and released individually // ex: [somthing].[something].[something] is bad //release com objects to fully kill excel process from running in the background Marshal.ReleaseComObject(xlRange); Marshal.ReleaseComObject(xlWorksheet); //close and release xlWorkbook.Close(); Marshal.ReleaseComObject(xlWorkbook); //quit and release xlApp.Quit(); Marshal.ReleaseComObject(xlApp); } static void Main(string[] args) { getExcelFile(); Console.Read(); } } }
Xem thêm:
CHÚC CÁC BẠN THÀNH CÔNG VÀ VUI VẺ
The post Mở Đọc File Excel Trong C# Với Microsoft Office Interop Excel dll appeared first on Tân Hồng IT.
]]>The post Mở và Đọc File Word Trong C# Với Microsoft Office Interop Word dll appeared first on Tân Hồng IT.
]]>Với NET 4+ cho phép C # đọc và thao tác các tệp Microsoft Word Excel, đối với các máy tính đã cài đặt Word, Excel (nếu bạn chưa cài đặt Word, Excel, hãy xem NPOI ).
Đầu tiên, thêm tham chiếu vào Thư viện đối tượng Microsoft Word XX.X , nằm trong tab COM của Trình quản lý tham chiếu. Mình đã đưa ra điều này bằng cách sử dụng bí danh của Word, Excel.
using Word = Microsoft.Office.Interop.Word; //Microsoft Word 14 object in references-> COM tab
Nếu các bạn cảm thấy khó khăn ở bước trên mình sẽ hướng dẫn chi tiết về bước trên cho các bạn tại đây.
Bạn bắt buộc phải tải DLL Microsoft.Office.Interop.Word về máy mới có thể hoàn thành bài code này.
Đây là link cập nhật phiên bản mới nhất: Download Microsoft.Office.Interop.Word.dll
Hoặc nếu link die thì các bạn cũng có thể Download Phiên bản 15.0.4603.1000
Tiếp theo Bạn tạo 1 Project Console App(.Net Framework)
Trong Solution Explorer , bấm chuột phải vào tên dự án của bạn và sau đó bấm Add Reference . Các Add Reference hộp thoại sẽ xuất hiện.
Trên trang Assemblies, click chọn Microsoft.Office.Interop.Word trong danh sách Component Name . sau đó nhấn và giữ phím CTRL và chọn Microsoft.Office.Interop.Excel nếu có. Và nhấn OK.
Sau khi đã làm những bước trên bạn có thể thêm tham chiếu vào thư viện được rồi.
using Excel = Microsoft.Office.Interop.Excel; using Word = Microsoft.Office.Interop.Word;
Và cuối cùng bạn chỉ cần thêm đoạn code này vào file Program.cs
class Program { static void Main(string[] args) { Application word = new Application(); object miss = System.Reflection.Missing.Value; object path = @"D:\HKIII\1. BTCL\tuan4_chuong2_3\docfileword\myDocument.docx"; object readOnly = true; object missing = System.Type.Missing; Document doc = word.Documents.Open(ref path, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss); string totalText = ""; for (int i = 0; i < doc.Paragraphs.Count; i++) { totalText += "\r\n" + doc.Paragraphs[i + 1].Range.Text.ToString(); } Console.WriteLine(totalText); Console.Read(); } }
Tại line thứ 7, các bạn nhớ sửa lại đường dẫn đến file word trong máy tính của mình nhé!
Và nhớ truyền đầy đủ các thư viện vào nhé!
Đây là Code đầy đủ để đọc và mở 1 file Word C# :
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Office.Interop.Word; namespace docfileword { class Program { static void Main(string[] args) { //Create COM Objects. Create a COM object for everything that is referenced Application word = new Application(); object miss = System.Reflection.Missing.Value; object path = @"D:\HKIII\1. BTCL\tuan4_chuong2_3\docfileword\myDocument.docx"; object readOnly = true; object missing = System.Type.Missing; Document doc = word.Documents.Open(ref path, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss); string totalText = ""; for (int i = 0; i < doc.Paragraphs.Count; i++) { totalText += "\r\n" + doc.Paragraphs[i + 1].Range.Text.ToString(); } Console.WriteLine(totalText); Console.Read(); } } }
Tài liệu tham khảo:
Xem thêm:
CHÚC CÁC BẠN THÀNH CÔNG VÀ VUI VẺ
The post Mở và Đọc File Word Trong C# Với Microsoft Office Interop Word dll appeared first on Tân Hồng IT.
]]>