C#实现对EXCEL指定单元格进行操作

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Office.Interop.Excel;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using Microsoft.Office.Core;

namespace HustCAD.IntePLM.Win.BatchEnterWinUI
{
    public class SighExcel
    {
        #region DllImport Methods
        [System.Runtime.InteropServices.DllImport("User32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
        public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int ID);
        #endregion

        Microsoft.Office.Interop.Excel.ApplicationClass application = null;
        Microsoft.Office.Interop.Excel.Workbook workBook = null;
        Microsoft.Office.Interop.Excel.Worksheet wSheet = null;

        /// <summary>
        /// 对EXCEL指定单元格进行操作
        /// </summary>
        /// <param name="filePath">EXCEL表格所在路径</param>
        /// <param name="row">行号</param>
        /// <param name="column">列号</param>
        /// <param name="code">内容</param>
        /// <returns></returns>
        public bool signExcel(string filePath, int row, int column, string code)
        {
            System.Globalization.CultureInfo CurrentCI = System.Threading.Thread.CurrentThread.CurrentCulture;
            System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");

            object missing = Type.Missing;
            try
            {
                try
                {
                    application = new Microsoft.Office.Interop.Excel.ApplicationClass();
                }
                catch (Exception e)
                {
                    System.IO.File.AppendAllText(System.IO.Path.Combine(GetCurrentPath(), "signExcellog.txt"), "文件" + filePath + "签入编号失败! ,错误:" + e.Message.ToString() + "。  " + DateTime.Now.ToString("yyyy-MM-dd-hh:mm:ss"));
                }
                if (application == null)
                {
                    System.IO.File.AppendAllText(System.IO.Path.Combine(GetCurrentPath(), "signExcellog.txt"), "文件" + filePath + "签入编号失败! " + DateTime.Now.ToString("yyyy-MM-dd-hh:mm:ss"));
                }

                application.AlertBeforeOverwriting = false;
                application.AskToUpdateLinks = false;
                application.AutomationSecurity = MsoAutomationSecurity.msoAutomationSecurityLow;
                application.DisplayAlerts = false;

                workBook = application.Workbooks.Open(filePath, missing, false, missing, missing, missing,
                        true, missing, missing, missing, missing, missing, missing, missing, missing);
                workBook.CheckCompatibility = false;//兼容性检查
                workBook.DoNotPromptForConvert = true;

                wSheet = (Worksheet)workBook.Worksheets[1];
                wSheet.Cells[row, column] = code;
                Microsoft.Office.Interop.Excel.Range rtemp = wSheet.get_Range(wSheet.Cells[3, 4], wSheet.Cells[3, 6]);
                rtemp.Font.Name = "宋体";
                rtemp.Font.Size = 12;
                object RouteWorkbook = false;
                object SaveChanges = XlSaveAction.xlSaveChanges;
                //wBook.SaveAs(filePath, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                workBook.Save();
                workBook.Close(SaveChanges, filePath, RouteWorkbook);
                return true;
            }
            catch (Exception e)
            {
                System.IO.File.AppendAllText(System.IO.Path.Combine(GetCurrentPath(), "signExcellog.txt"), "文件" + filePath + "签入编号失败! ,错误:" + e.Message.ToString() + "。  " + DateTime.Now.ToString("yyyy-MM-dd-hh:mm:ss"));
                return false;
            }
            finally
            {
                if (workBook != null)
                {
                    workBook.Close(true, missing, missing);
                    workBook = null;
                }
                if (application != null)
                {
                    application.Quit();
                    KillSpecialExcel(application);
                    application = null;
                }
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }

        /// <summary>
        /// Kill Special Excel Process
        /// </summary>
        public static void KillSpecialExcel(Application m_objExcel)
        {
            try
            {
                if (m_objExcel != null)
                {
                    int lpdwProcessId;
                    GetWindowThreadProcessId(new IntPtr(m_objExcel.Hwnd), out lpdwProcessId);
                    System.Diagnostics.Process.GetProcessById(lpdwProcessId).Kill();
                }
            }
            catch (Exception)
            {}
        }
        
        public string getCellValue(string filePath, int row, int column)
        {
            System.Globalization.CultureInfo CurrentCI = System.Threading.Thread.CurrentThread.CurrentCulture;
            System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");

            object missing = Type.Missing;
            try
            {
                try
                {
                    application = new Microsoft.Office.Interop.Excel.ApplicationClass();
                }
                catch (Exception e)
                {
                    System.IO.File.AppendAllText(System.IO.Path.Combine(GetCurrentPath(), "signExcellog.txt"), "文件" + filePath + "签入编号失败! ,错误:" + e.Message.ToString() + "。  " + DateTime.Now.ToString("yyyy-MM-dd-hh:mm:ss"));
                }
                if (application == null)
                {
                    System.IO.File.AppendAllText(System.IO.Path.Combine(GetCurrentPath(), "signExcellog.txt"), "文件" + filePath + "签入编号失败! " + DateTime.Now.ToString("yyyy-MM-dd-hh:mm:ss"));
                }

                application.AlertBeforeOverwriting = false;
                application.AskToUpdateLinks = false;
                application.AutomationSecurity = MsoAutomationSecurity.msoAutomationSecurityLow;
                application.DisplayAlerts = false;

                workBook = application.Workbooks.Open(filePath, missing, false, missing, missing, missing,
                        true, missing, missing, missing, missing, missing, missing, missing, missing);
                workBook.CheckCompatibility = false;//兼容性检查
                workBook.DoNotPromptForConvert = true;

                wSheet = (Worksheet)workBook.Worksheets[1];
                return ((Microsoft.Office.Interop.Excel.Range)wSheet.Cells[row, column]).Text.ToString().Trim();
            }
            catch (Exception e)
            {
                System.IO.File.AppendAllText(System.IO.Path.Combine(GetCurrentPath(), "signExcellog.txt"), "文件" + filePath + "签入编号失败! ,错误:" + e.Message.ToString() + "。  " + DateTime.Now.ToString("yyyy-MM-dd-hh:mm:ss"));
                return "";
            }
            finally
            {
                if (workBook != null)
                {
                    workBook.Close(true, missing, missing);
                    workBook = null;
                }
                if (application != null)
                {
                    application.Quit();
                    KillSpecialExcel(application);
                    application = null;
                }
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }

        /// <summary>
        /// 得到当前程序的路径
        /// </summary>
        /// <returns></returns>
        static public string GetCurrentPath()
        {
            string asstring = Assembly.GetExecutingAssembly().Location;
            string[] aa = asstring.Split('\\');
            string path = string.Empty;
            foreach (string var in aa)
            {
                if (var != aa[aa.Length - 1])
                    path += var + @"\";
            }
            return path;
        }
    }
}

  

转载于:https://www.cnblogs.com/Acamy/p/5882849.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
range.NumberFormatLocal = "@"; //设置单元格格式为文本 range = (Range)worksheet.get_Range("A1", "E1"); //获取Excel多个单元格区域:本例做为Excel表头 range.Merge(0); //单元格合并动作 worksheet.Cells[1, 1] = "Excel单元格赋值"; //Excel单元格赋值 range.Font.Size = 15; //设置字体大小 range.Font.Underline=true; //设置字体是否有下划线 range.Font.Name="黑体"; 设置字体的种类 range.HorizontalAlignment=XlHAlign.xlHAlignCenter; //设置字体在单元格内的对其方式 range.ColumnWidth=15; //设置单元格的宽度 range.Cells.Interior.Color=System.Drawing.Color.FromArgb(255,204,153).ToArgb(); //设置单元格的背景色 range.Borders.LineStyle=1; //设置单元格边框的粗细 range.BorderAround(XlLineStyle.xlContinuous,XlBorderWeight.xlThick,XlColorIndex.xlColorIndexAutomatic,System.Drawing.Color.Black.ToArgb()); //给单元格加边框 range.Borders.get_Item(Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeTop).LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlLineStyleNone; //设置单元格上边框为无边框 range.EntireColumn.AutoFit(); //自动调整列宽 Range.HorizontalAlignment= xlCenter; // 文本水平居中方式 Range.VerticalAlignment= xlCenter //文本垂直居中方式 Range.WrapText=true; //文本自动换行 Range.Interior.ColorIndex=39; //填充颜色为淡紫色 Range.Font.Color=clBlue; //字体颜色 xlsApp.DisplayAlerts=false; //保存Excel的时候,不弹出是否保存的窗口直接进行保存 ==================================================================== using System; using System.Collections.Generic; using System.Text; using System.Reflection; using System.Runtime.InteropServices; using Microsoft.Office.Interop.Excel; using ExcelApplication = Microsoft.Office.Interop.Excel.ApplicationClass; using System.IO; namespace ExcalDemo { public class ExcelFiles { public void CreateExcelFiles() { ExcelApplication excel = new ExcelApplication(); try { excel.Visible = false;// 不显示 Excel 文件,如果为 true 则显示 Excel 文件 excel.Workbooks.Add(Missing.Value);// 添加工作簿 Worksheet sheet = (Worksheet)excel.ActiveSheet;// 获取当前工作表 Range range = null;// 创建一个空的单元格对象 range = sheet.get_Range("A1", Missing.Value);// 获取单个单元格 range.RowHeight = 20; // 设置行高 range.ColumnWidth = 20; // 设置列宽 range.Borders.LineStyle = 1; // 设置单元格边框 range.Font.Bold = true; // 加粗字体 range.Font.Size = 20; // 设置字体大小 range.Font.ColorIndex = 5; // 设置字体颜色 range.Interior.ColorIndex = 6; // 设置单元格背景色 range.HorizontalAlignment = XlHAlign.xlHAlignCenter;// 设置单元格水平居中 range.VerticalAlignment = XlVAlign.xlVAlignCenter;// 设置单元格垂直居中 range.Value2 = "设置行高和列宽";// 设置单元格的值 range = sheet.get_Range("B2", "D4");// 获取多个单元格 range.Merge(Missing.Value); // 合并单元格 range.Columns.AutoFit(); // 设置列宽为自动适应 range.NumberFormatLocal = "#,##0.00";// 设置单元格格式为货币格式 // 设置单元格左边框加粗 range.Borders[XlBordersIndex.xlEdgeLeft].Weight = XlBorderWeight.xlThick; // 设置单元格右边框加粗 range.Borders[XlBordersIndex.xlEdgeRight].Weight = XlBorderWeight.xlThick; range.Value2 = "合并单元格"; // 页面设置 sheet.PageSetup.PaperSize = XlPaperSize.xlPaperA4; // 设置页面大小为A4 sheet.PageSetup.Orientation = XlPageOrientation.xlPortrait; // 设置垂直版面 sheet.PageSetup.HeaderMargin = 0.0; // 设置页眉边距 sheet.PageSetup.FooterMargin = 0.0; // 设置页脚边距 sheet.PageSetup.LeftMargin = excel.InchesToPoints(0.354330708661417); // 设置左边距 sheet.PageSetup.RightMargin = excel.InchesToPoints(0.354330708661417);// 设置右边距 sheet.PageSetup.TopMargin = excel.InchesToPoints(0.393700787401575); // 设置上边距 sheet.PageSetup.BottomMargin = excel.InchesToPoints(0.393700787401575);// 设置下边距 sheet.PageSetup.CenterHorizontally = true; // 设置水平居中 // 打印文件 sheet.PrintOut(Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value); // 保存文件到程序运行目录下 sheet.SaveAs(Path.Combine(System.Windows.Forms.Application.StartupPath,"demo.xls"), Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value); excel.ActiveWorkbook.Close(false, null, null); // 关闭 Excel 文件且不保存 } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { excel.Quit(); // 退出 Excel excel = null; // 将 Excel 实例设置为空 } } } }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值