导出数据到excel

摘要:
//写入(int r=0;4]=data[r].Cas;5]=data[r].ProductName;7]=data[r.].Price;8]=data[r].ProductNameOfPurchaseInvoice;=“”){try{workbook.Saved=true;fileSaved=true;=null){xlApp.Quit();

第一种方式  :需引用 Microsoft.Office.Interop.Excel,安装office

       public bool ExportToExcel()

       {

Microsoft.Office.Interop.Excel.Application xlApp;
try
{
xlApp = new Microsoft.Office.Interop.Excel.Application();
}
catch (Exception ex)
{
xlApp = null;
GC.Collect();//强行销毁
return false
}
finally
{
}
Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;
Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];//取得sheet1
//写Title
var titleRowCount = 0;

if (titleRowCount != 0)
MergeCells(worksheet, 1, 1, titleRowCount, 8, "销售代开发票");

//写入列标题
worksheet.Cells[titleRowCount + 1, 1] = "序号";
worksheet.Cells[titleRowCount + 1, 2] = "发货时间";
worksheet.Cells[titleRowCount + 1, 3] = "销售订单号";
worksheet.Cells[titleRowCount + 1, 4] = "CAS";
worksheet.Cells[titleRowCount + 1, 5] = "产品名称";
worksheet.Cells[titleRowCount + 1, 6] = "包装";
worksheet.Cells[titleRowCount + 1, 7] = "价格";
worksheet.Cells[titleRowCount + 1, 8] = "开票产品名称";

//写入数值
for (int r = 0; r <= data.Count - 1; r++)
{
worksheet.Cells[r + titleRowCount + 2, 1] = r + 1;

worksheet.Cells[r + titleRowCount + 2, 2] = data[r].SendGoodDate;
worksheet.Cells[r + titleRowCount + 2, 3] = data[r].SaleOderNumber;
worksheet.Cells[r + titleRowCount + 2, 4] = data[r].Cas;
worksheet.Cells[r + titleRowCount + 2, 5] = data[r].ProductName;
worksheet.Cells[r + titleRowCount + 2, 6] = data[r].PackAge;
worksheet.Cells[r + titleRowCount + 2, 7] = data[r].Price;
worksheet.Cells[r + titleRowCount + 2, 8] = data[r].ProductNameOfPurchaseInvoice;

}
worksheet.Columns.EntireColumn.AutoFit();//列宽自适应
bool fileSaved = true;
if (saveFileName != "")
{
try
{
workbook.Saved = true;
workbook.SaveCopyAs(Server.MapPath(saveFileName));
fileSaved = true;
}
catch (Exception ex)
{
fileSaved = false;
if (workbook != null)
{
workbook.Close(true, Type.Missing, Type.Missing);
workbook = null;
}
if (workbooks != null)
{
workbooks.Close();
workbooks = null;
}
if (xlApp != null)
{
xlApp.Quit();
if (xlApp != null)
{
int lpdwProcessId;


GetWindowThreadProcessId(new IntPtr(xlApp.Hwnd), out lpdwProcessId);

System.Diagnostics.Process.GetProcessById(lpdwProcessId).Kill();
}
xlApp = null;
}
GC.Collect();//强行销毁
}
}

if (workbook != null)
{
workbook.Close(true, Type.Missing, Type.Missing);
workbook = null;
}
if (workbooks != null)
{
workbooks.Close();
workbooks = null;
}
if (xlApp != null)
{
xlApp.Quit();
}
GC.Collect();//强行销毁
if (xlApp != null)
{
int lpdwProcessId;


GetWindowThreadProcessId(new IntPtr(xlApp.Hwnd), out lpdwProcessId);

System.Diagnostics.Process.GetProcessById(lpdwProcessId).Kill();
}
xlApp = null;
if (!fileSaved)
{
return false;
}
return true;

}

 

/// <summary>
/// 合并单元格,并赋值,对指定WorkSheet操作
/// </summary>
/// <param name="sheetIndex">WorkSheet索引</param>
/// <param name="beginRowIndex">开始行索引</param>
/// <param name="beginColumnIndex">开始列索引</param>
/// <param name="endRowIndex">结束行索引</param>
/// <param name="endColumnIndex">结束列索引</param>
/// <param name="text">合并后Range的值</param>
public void MergeCells(Microsoft.Office.Interop.Excel.Worksheet workSheet, int beginRowIndex, int beginColumnIndex, int endRowIndex, int endColumnIndex, string text)
{
       Microsoft.Office.Interop.Excel.Range range = workSheet.get_Range((object)workSheet.Cells[beginRowIndex, beginColumnIndex], (object)workSheet.Cells[endRowIndex, endColumnIndex]);
  range.ClearContents(); //先把Range内容清除,合并才不会出错
  range.MergeCells = true;
  range.Value2 = text;
  range.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
  range.VerticalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;
}

[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int ID);

 

第二种方式:服务器端无需安装office

1.在服务器放置一空excel文件

2.copy一份新excel

3.导出数据到该excel

public static string GetSaleOrderWaitPendingInvoiceExportExcelPath(DataTable dt, string templateFileName, string exportFileName)
{

  if (string.IsNullOrEmpty(templateFileName) || string.IsNullOrEmpty(templateFileName))
  {
    return "路径空";
  }

  File.Copy(templateFileName, exportFileName);

  OleDbConnection OleDb_Conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + exportFileName + ";" + "Extended Properties="Excel 12.0 Xml;HDR=Yes;IMEX=0;"");
  try
  {
    OleDb_Conn.Open();
    OleDbCommand OleDb_Comm = new OleDbCommand();
    OleDb_Comm.Connection = OleDb_Conn;
    string strCmd;

    try
    {
      strCmd = "drop table [Sheet1$]";
      OleDb_Comm.CommandText = strCmd;
      OleDb_Comm.ExecuteNonQuery();
    }
    catch
    {
    }


    strCmd = "create Table [Sheet1$](";

    strCmd += "[序号] TEXT,"; //此处 TEXT 是为了 防止导出数据的长度大于255而导出异常
    strCmd += "[发货时间] TEXT,";
    strCmd += "[销售订单号] TEXT,";
    strCmd += "[CAS] TEXT,";
    strCmd += "[产品名称] TEXT,";
    strCmd += "[包装] TEXT,";
    strCmd += "[价格] TEXT,";
    strCmd += "[开票产品名称] TEXT,";
    strCmd = strCmd.Trim().Substring(0, strCmd.Length - 1);
    strCmd += ")";
    OleDb_Comm.CommandText = strCmd;
    OleDb_Comm.ExecuteNonQuery();

    StringBuilder CommText = new StringBuilder();
    foreach (DataRow dr in dt.Rows)
    {
      CommText.Append("INSERT INTO [Sheet1$] VALUES(");
      CommText.Append("'" + dr[0].ToString().Replace("'","''") + "',");
      CommText.Append("'" + dr[1].ToString().Replace("'", "''") + "',");
      CommText.Append("'" + dr[2].ToString().Replace("'", "''") + "',");
      CommText.Append("'" + dr[3].ToString().Replace("'", "''") + "',");
      CommText.Append("'" + dr[4].ToString().Replace("'", "''") + "',");
      CommText.Append("'" + dr[5].ToString().Replace("'", "''") + "',");
      CommText.Append("'" + dr[6].ToString().Replace("'", "''") + "',");
      CommText.Append("'" + dr[7].ToString().Replace("'", "''") + "'");
      CommText.Append(");");


      //导出数据
      OleDb_Comm.CommandText = CommText.ToString().Replace(':', ';').TrimEnd(';');
      OleDb_Comm.ExecuteNonQuery();

      CommText.Remove(0, CommText.Length);
    }
  }
  catch
  {
    OleDb_Conn.Close();
    return "导出数据时报错";
  }
  OleDb_Conn.Close();
  return "";
}

 

免责声明:文章转载自《导出数据到excel》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇14.深入k8s:kube-proxy ipvs及其源码分析python操作excel以及word文档,pdf文档下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

配置RedisTemplate、JedisPoolConfig、JedisConnectionFactory+自定义序列化 (xml+java方式)+使用

java方式配置RedisTemplate   //spring注入ben    //@Bean(name = "redisTemplate") public RedisTemplate initRedisTemplate(){ JedisPoolConfig poolConfig = new JedisPoolConfig();...

链表面试题

1、逆置链表 假设链表现在是 4->3->2->1->NULL逆置后的链表是 1->2->3->4->NULL步骤:第一步:先把4用临时指针tmp保存起来,cur指向下一个节点,即cur指向3 第二步:令tmp指向newNode,4是第一个节点,则4的next为NULL,即令tmp->next =ne...

禁止crontab -r清空定时任务列表误操作

关于crontab 1、附件cron.sh放/usr/bin目录下面 2、在/etc/bashrc文件末尾添加 alias crontab='/usr/bin/cron.sh'  或者在当前root用户下在~/.bashrc文件末尾添加:alias crontab='/usr/bin/cron.sh'  ==========================...

使用VsCode的Rest Client进行请求测试

平时工作使用VSCode进行request的提交和测试 =>{按照Rest Client 可以很轻松的帮助我们完成代码的调试,而且能帮我们编译成各种语言的代码使用(Generate Code Snippet)} 如下表:我是用了Get请求,然后Shift+Ctrl+P进入VsCode的命令行,然后选择 Rest Client:Generate Cod...

阿里人脸识别接口

最近研究了一下阿里的人脸识别功能,只是调用阿里提供的接口返回数据给我们就OK了。详细文档可参考阿里的api  阿里人脸识别api 人脸比对的方法 直接上代码吧: 1 package com.guoxin.common.test; 2 3 import sun.misc.BASE64Encoder; 4 import javax.cryp...

【转】WPF自定义控件与样式(8)-ComboBox与自定义多选控件MultComboBox

一.前言   申明:WPF自定义控件与样式是一个系列文章,前后是有些关联的,但大多是按照由简到繁的顺序逐步发布的等。   本文主要内容: 下拉选择控件ComboBox的自定义样式及扩展; 自定义多选控件MultiComboBox; 二.下拉选择控件ComboBox的自定义样式及扩展 2.1基本样式   先看看基础效果图:     从功能上ComboBo...