首页 > 编程语言 >C++/CLI使用Office.Interop库创建excel,同时解决写入速度慢的问题

C++/CLI使用Office.Interop库创建excel,同时解决写入速度慢的问题

时间:2024-10-26 20:32:14浏览次数:6  
标签:CLI Office Missing Interop Excel nullptr worksheet workbook Type

bool WriteExcelFile_OfficeInterop(String^ path, DataSet^ dt,
		const std::vector<std::string>& sheetName, bool hideColumnName)
	{
		// If the file already exists, delete it and then generate file
		if (System::IO::File::Exists(path))
		{
			try
			{
				System::IO::File::Delete(path);
			}
			catch (System::Exception^ e)
			{
				System::Windows::Forms::MessageBox::Show("Delete Excel File Failed, Please Check File Statue.",
					"Delete File Error",
					System::Windows::Forms::MessageBoxButtons::OK,
					System::Windows::Forms::MessageBoxIcon::Error);
				return false;
			}
		}

		Excel::Application^ excelApp = nullptr;
		Excel::_Workbook^ workbook = nullptr;
		Excel::Worksheet^ worksheet = nullptr;
		Excel::Range^ range = nullptr;
		Excel::Range^ firstRow = nullptr;
		Excel::Sort^ sort = nullptr;
		bool ret = true;
		try
		{
			//Create a new instance of Excel application
			excelApp = gcnew Excel::ApplicationClass();
			//Create a new workbook
			workbook = excelApp->Workbooks->Add(true);

			for (int i = 0; i < dt->Tables->Count; ++i)
			{
				//Create a new worksheet
				worksheet = (Excel::Worksheet^)workbook->Sheets->Add(Type::Missing, workbook->Sheets[workbook->Worksheets->Count], Type::Missing, Excel::XlSheetType::xlWorksheet);
				//Set the name of the worksheet
				worksheet->Name = StringToSystemString(sheetName[i]);

				// headerRowIndex == 0 means that header is hid
				int headerRowIndex = 0;
				if (hideColumnName == false)
				{
					// the header will occupy 1 row
					headerRowIndex = 1;
					//Fill the header row with column names
					for (int j = 0; j < dt->Tables[i]->Columns->Count; ++j)
					{
						worksheet->Cells[1, j + 1] = dt->Tables[i]->Columns[j]->ColumnName;
					}
				}

				//Fill the data rows using range object
				int numCols = dt->Tables[i]->Columns->Count;
				int numRows = dt->Tables[i]->Rows->Count;
				range = worksheet->Range[worksheet->Cells[headerRowIndex + 1, 1], 
										 worksheet->Cells[headerRowIndex + numRows, numCols]];

				// 使用二维数组加速写入
				array<System::Object^, 2>^ dataArray = gcnew array<System::Object^, 2>(numRows, numCols);
				for (int row = 0; row < numRows; ++row)
				{
					for (int col = 0; col < numCols; ++col)
					{
						dataArray[row, col] = dt->Tables[i]->Rows->default[row]->default[col];
					}
				}
				range->Value2 = dataArray;
				
				// UsedRange : not empty column
				worksheet->UsedRange->Columns->AutoFit();
			}
			// delete default empty sheet which is created when create a workbook
			safe_cast<Excel::Worksheet^>(workbook->Sheets["Sheet1"])->Delete();
			// select the first sheet
			safe_cast<Excel::_Worksheet^>(workbook->Sheets[1])->Activate();
			//Save the workbook
			workbook->SaveAs(path, Type::Missing, Type::Missing,
				Type::Missing, Type::Missing, Type::Missing, Microsoft::Office::Interop::Excel::XlSaveAsAccessMode::xlNoChange,
				Type::Missing, Type::Missing, Type::Missing, Type::Missing, Type::Missing);

			//Close the workbook
			workbook->Close(Type::Missing, Type::Missing, Type::Missing);

			//Quit the Excel application
			excelApp->Quit();
		}
		catch (System::Exception^ e)
		{
			System::Windows::Forms::MessageBox::Show(e->Message,
				"Write File Error",
				System::Windows::Forms::MessageBoxButtons::OK,
				System::Windows::Forms::MessageBoxIcon::Error);

			//Close the workbook and quit the Excel application
			if (workbook != nullptr)
			{
				workbook->Close(Type::Missing, Type::Missing, Type::Missing);
			}
			if (excelApp != nullptr)
			{
				excelApp->Quit();
			}
			ret = false;
		}
		finally
		{
			//Release COM objects
			if (sort != nullptr)
			{
				Marshal::ReleaseComObject(sort);
			}
			if (firstRow != nullptr)
			{
				Marshal::ReleaseComObject(firstRow);
			}
			if (range != nullptr)
			{
				Marshal::ReleaseComObject(range);
			}

			if (worksheet != nullptr)
			{
				Marshal::ReleaseComObject(worksheet);
			}
			if (workbook != nullptr)
			{
				Marshal::ReleaseComObject(workbook);
			}
			if (excelApp != nullptr)
			{
				Marshal::ReleaseComObject(excelApp);
			}
		}
		return ret;
	}

标签:CLI,Office,Missing,Interop,Excel,nullptr,worksheet,workbook,Type
From: https://www.cnblogs.com/sandersshine/p/18504461

相关文章

  • C++/CLI 类内多线程编程 多个参数
    usingnamespaceSystem;usingnamespaceSystem::Threading;namespaceNNNN{ publicrefclassTTTT { staticThread^t1; staticThread^t2; voidfun() { t1=gcnewThread(gcnewParameterizedThreadStart(DoWork1)); t2=gcnewThread(gcnewP......
  • Bd-Ticket-Guard-Client-Data逆向
    'Bd-Ticket-Guard-Client-Data':'eyJ0c19zaWduIjoidHMuMS43ODhkMTE1OTUwMTM1NDVhNjg5M2I0OGU3NTQ2NDk5NjZjNTMyYzBhZmMxMjRjMTUwNGQ1OTVjNDJiOWI1ZDk0YzRmYmU4N2QyMzE5Y2YwNTMxODYyNGNlZGExNDkxMWNhNDA2ZGVkYmViZWRkYjJlMzBmY2U4ZDRmYTAyNTc1ZCIsInJlcV9jb250Z......
  • 使用Clickhouse数据库后,硬盘占满了,怎么办
    Hello,大家好,在我们使用了clickhouse进行数据存储后,多多少少遇到一些棘手的问题,在此记录。我们使用clickhouse改造后,系统流畅度得到大幅提升,大家有兴趣可以来体验一下效果,Webfunny前端监控和埋点系统如大家所知,Clickhouse数据有几大优点,很适合处理海量的数据,如:查询效率高、clickh......
  • 基于CLIP的关键帧选择策略
    基于CLIP的关键帧选择策略:原理这种方法将整个视频划分为多个片段(clips),并从每个片段中提取能够代表该片段的关键帧。具体过程如下:使用CLIP提取特征:第一步是使用CLIP模型对视频的第一帧进行编码,生成特征向量,该向量包含了该帧的高级语义信息。CLIP能够将图像的视觉内容压缩为......
  • HttpClient—请求第三方的服务
    1.介绍1.1简介HttpClient是ApacheJakartaCommons项目中的一个子项目,为开发人员提供了一个高效、功能丰富、支持最新HTTP协议的客户端工具包。它不仅可以支持HTTP/1.1和HTTP/2等最新版本的HTTP协议,还包括一系列高级特性,如连接池管理、SSL支持、自动重试机制、......
  • DA-CLIP-universal-image-restoration代码详解
    DA-CLIP-universal-image-restoration代码详解创建模型model=create_model(opt)device=model.devicecreat_model最终指向ConditionalUNet类,类的主要结构如下:classConditionalUNet(nn.Module):def__init__(self,in_nc,out_nc,nf,ch_mult=[1,......
  • HttpClient请求结果
    好的,你想要循环遍历对象列表,对每个GET请求执行HTTP请求,并检查响应状态码是否为200。如果状态码不是200,就打印出响应体。为了实现这个功能,可以使用HttpClient库,它更现代和灵活。以下是一个示例代码,演示如何实现上述需求:首先,添加依赖(如果你使用Maven),在pom.xml中添加HttpClient库......
  • C# UDP组播客户端【UDPClient】
    方式一UdpClientudp=newUdpClient(5566);//要通过其进行通信的本地端口号。5566是源端口udp.JoinMulticastGroup(IPAddress.Parse("224.0.0.4"));//将UdpClient添加到多播组;IPAddress.Parse将IP地址字符串转换为IPAddress实例IPEndPointmu......
  • 创建一个专属的 CLI
    作为一个前端,基本上每次初始化项目都会用到脚手架,通过一些脚手架可以快速的搭建一个前端的项目并集成一些所需的功能模块,避免自己每次都手动一个一个去安装。安装各个包的这个过程其实没啥营养,通过封装一个脚手架来跳过这个步骤,把精力聚焦到功能研发上。由于最近自己在写项目都是......
  • vue-cli 跳转到页面指定位置
    原文关注公众号,后台里留言可进行提问,可在后台留言向作者提问解答问题!https://mp.weixin.qq.com/s?__biz=Mzg3NTAzMzAxNA==&mid=2247484254&idx=1&sn=361bbb2113be3eeda3802f0a805c5705&chksm=cec6fb87f9b1729174e3ae66bf9693207386256c964499c098fb8a6cc14b4ba266bc271073a3&tok......