c#讀寫excel
阿新 • • 發佈:2020-04-20
using System; using System.Data; using Excel= Microsoft.Office.Interop.Excel; namespace 讀寫excel { /// <summary> /// MainWindow.xaml 的互動邏輯 /// </summary> public partial class MainWindow { public MainWindow() { InitializeComponent(); // ReSharper disable once UnusedVariable//var x = GetData("d:\\1.xlsx"); //GC.Collect(); //GC.WaitForPendingFinalizers(); //GC.Collect(); // test("d:\\1.xlsx"); DataTable dt = new DataTable(); dt.Columns.Add(new DataColumn("sasfadf")); dt.Columns.Add(new DataColumn("sasfadf2")); dt.Columns.Add(new DataColumn("sasfadfss三代富貴")); for (int i = 0; i < 10; i++) { DataRow dr = dt.NewRow(); dr[0] = "1234"; dr[2] = "薩芬"; dr[1] = "asdfha"; dt.Rows.Add(dr); }string errMsg; bool ok= Set(dt,"d:\\32.xlsx",out errMsg); } static DataTable GetData(string excelFilePath,bool hasTitle = false) { var app = new Excel.Application(); object oMissiong = System.Reflection.Missing.Value; Excel._Workbook workbook = null; var dt = new DataTable(); try { workbook = app.Workbooks.Open(excelFilePath,oMissiong,oMissiong); var sheets = workbook.Worksheets; //將資料讀入到DataTable中 var worksheet = (Excel.Worksheet)sheets.Item[1];//讀取第一張表 if (worksheet == null) return null; var iRowCount = worksheet.UsedRange.Rows.Count; var iColCount = worksheet.UsedRange.Columns.Count; //生成列頭 for (var i = 0; i < iColCount; i++) { var name = "column" + i; if (hasTitle) { var txt = ((Excel.Range)worksheet.Cells[1,i + 1]).Text.ToString(); if (!string.IsNullOrWhiteSpace(txt)) name = txt; } while (dt.Columns.Contains(name)) name = name + "_1";//重複行名稱會報錯。 dt.Columns.Add(new DataColumn(name,typeof(string))); } //生成行資料 var rowIdx = hasTitle ? 2 : 1; for (var iRow = rowIdx; iRow <= iRowCount; iRow++) { var dr = dt.NewRow(); for (var iCol = 1; iCol <= iColCount; iCol++) { var range = (Excel.Range)worksheet.Cells[iRow,iCol]; dr[iCol - 1] = (range.Value2 == null) ? "" : range.Text.ToString(); } dt.Rows.Add(dr); } return dt; } catch { return null; } finally { if (workbook != null) { workbook.Close(false,oMissiong); System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook); } app.Workbooks.Close(); app.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(app); } } private static bool Set(DataTable dt,string excelFilePath,out string errMsg ) { Microsoft.Office.Interop.Excel.Application app = null; Microsoft.Office.Interop.Excel._Workbook workbook = null; object oMissiong = System.Reflection.Missing.Value; try { app = new Microsoft.Office.Interop.Excel.Application(); app.DisplayAlerts = false; workbook = app.Workbooks.Add(true); //將資料讀入到DataTable中 var worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets.Item[1]; //讀取第一張表 if (worksheet == null) { errMsg = "asdg"; return false; } var iRowCount = dt.Rows.Count; var iColCount =dt.Columns.Count; //生成列頭 for (var i = 0; i < iColCount; i++) { worksheet.Cells[1,i + 1] = dt.Columns[i].ColumnName; } for (var iRow = 2; iRow <= iRowCount; iRow++) { for (var iCol = 1; iCol <= iColCount; iCol++) { worksheet.Cells[iRow,iCol]=dt.Rows[iRow-2][iCol-1].ToString(); } } errMsg = ""; return true; } catch (Exception ex) { errMsg = ex.Message; return false; } finally { if (workbook != null) { workbook.Close(true,excelFilePath,oMissiong); System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook); } if (app != null) { app.Workbooks.Close(); app.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(app); } } } //void test(string sourceFile) //{ // var app = new Microsoft.Office.Interop.Excel.Application(); // var tp = app.GetType(); // var workBook = app.Workbooks; // var elType = workBook.GetType(); // object objelName = sourceFile; // var ebook = (Microsoft.Office.Interop.Excel.Workbook)elType.InvokeMember("Open",System.Reflection.BindingFlags.InvokeMethod,null,workBook,new Object[] { objelName,true,true }); // Object missing = System.Reflection.Missing.Value; // for (var i = 0; i < ebook.Worksheets.Count; i++) // { // Excel.Worksheet ws = ebook.Worksheets[i + 1]; // ws.PageSetup.Orientation = Excel.XlPageOrientation.xlPortrait;//頁面方向豎向 // ws.PageSetup.Zoom = false; // ws.PageSetup.FitToPagesWide = 1; // ws.PageSetup.FitToPagesTall = false; // } // ebook.PrintOut(missing,missing,"d:\\2.xps"); // tp.InvokeMember("Quit",app,null); // // workBook.Close(); // // app.Quit(); //} } }