C# 用spreadsheet打开excel文件

using System.IO;
using Microsoft.Office.Core;
using Excel = Microsoft.Office.Interop.Excel;

public bool OpenExcelInSpreadSheet()
{
 OpenFileDialog openFileDialog = new OpenFileDialog();
 openFileDialog.Filter = "Excel文件(*.xls)|*.xls|所有文件(*.*)|*.*";
 openFileDialog.Title = "选择要打开的文件";
 openFileDialog.ShowDialog();
 if (openFileDialog.FileName.Length > 0)
 {
  //将原文件拷贝一份到临时文件夹再打开备份文件,不推荐直接打开原文件,因为有可能该文件已经被打开了。
  //也不推荐将excel文件转换成xml文件再用spreadsheet打开,因为有的版本的excel格式转换到xml后不能正确打开。
  //本例临时文件夹为应用程序所在目录的“temp excel files”文件夹。
  string path = System.Windows.Forms.Application.ExecutablePath;
  FileInfo exeInfo = new FileInfo(path);
  path = exeInfo.DirectoryName + "\\";
  string tempExcel = path + "temp excel files\\" + openFileDialog.FileName.Split(new Char[] { '\\' }).Last();
  if (File.Exists(tempExcel))
  {
   string just_name = ofd.FileName.Split(new Char[] { '\\' }).Last();
   DialogResult result = MessageBox.Show(just_name + "已经存在,确认覆盖?", "文件上传提示", MessageBoxButtons.OKCancel);
   if (result == DialogResult.OK)
   {
    File.Copy(ofd.FileName, tempExcel, true);
    Excel.Application app = new Excel.Application();
    if (app == null)
    {
     MessageBox.Show("Excel打开失败!");
     return false;
    }
    app.Visible = false; 
    app.UserControl = true;
    Excel.Workbooks workbooks = app.Workbooks;
    Excel._Workbook workbook = workbooks.Open(newFileName, 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, null, null);
    app.DisplayAlerts = false;
    try
    {
     app.CopyObjectsWithCells = true;
     Excel._Worksheet sheet1 = (Excel._Worksheet)workbook.Sheets[1];    //打开sheet1
     sheet1.UsedRange.Copy(Type.Missing);          //复制sheet1到剪贴板
     AxMicrosoft.Office.Interop.Owc11.AxSpreadsheet spreadsheet = new AxMicrosoft.Office.Interop.Owc11.AxSpreadsheet();
     spreadsheet.get_Range(this.spreadsheet.Cells[1, 1]).Paste();    //将剪贴板复制的内容贴到spreadsheet上
    }
    catch (System.Exception exc)
    {
     MessageBox.Show(exc.Message);
     return false;
    }
    app.Quit();
    File.Delete(tempExcel);
    return true;
   }else
   {
    return false;
   }
  }
 }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_老杨_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值