精华内容
下载资源
问答
  • c#创建excel表格
    2022-05-19 13:27:00

    1、先将数据填充到DataTable中

    DataTable dataTable = new DataTable();
    dataTable.Columns.Add("ID");
    dataTable.Columns.Add("姓名");
    
    foreach (var student in Students)
    {
        DataRow dr = dataTable.NewRow();
        dr[0] = student.ID.ToString();
        dr[1] = student.Name.ToString();
                            
        dataTable.Rows.Add(dr);
    }
    
    //savePath为保存路径
    var savePath = "XXXXXX.xls";
    ExportExcel(dataTable, savePath);

    2、将DataTable中的数据按流的方式写入

    /// <summary>
    /// 写入Excel
    /// </summary>
    /// <param name="dataTable"></param>
    /// <param name="selectPath"></param>
    public static bool ExportExcel(DataTable dataTable, string selectPath)
    {
        try
        {
            string title = "";
            FileStream fs = new FileStream(selectPath, FileMode.OpenOrCreate);
            StreamWriter sw = new StreamWriter(new BufferedStream(fs), Encoding.Default);
    
            for (int i = 0; i < dataTable.Columns.Count; i++)
            {
                title += dataTable.Columns[i].ColumnName + "\t";
            }
    
            title = title.Substring(0, title.Length - 1) + "\n";
            sw.Write(title);
    
            foreach (DataRow row in dataTable.Rows)
            {
                string line = "";
    
                for (int i = 0; i < dataTable.Columns.Count; i++)
                {
                    line += row[i].ToString().Trim() + "\t";
                }
    
                line = line.Substring(0, line.Length - 1) + "\n";
                sw.Write(line);
            }
    
            sw.Close();
            fs.Close();
            return true;
        }
        catch (Exception ex)
        {
           
            return false;
        }
    }

     

    更多相关内容
  • 使用C#创建Excel表格、绘制图形 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; ...
  • .Net C# 读取Excel表格数据,根据表格数据结构在数据库新建一张对应的数据表既可以上传导入SQlServer数据库,代码有上传文件功能和解析表格数据功能,这里是建数据转成DataTable保存,导入速度对循环导入效率高很多...
  • C#创建EXCEL表格

    2013-05-08 15:42:00
    首先在。net引用中引用“Microsoft.Office.Interop.Excel” ... using MSExcel=Microsoft.Office.Interop.Excel; object missing = System.Reflection.Missing.Value; MSExcel.Application app = new...

    首先在。net引用中引用“Microsoft.Office.Interop.Excel”

            using MSExcel=Microsoft.Office.Interop.Excel;

      

     object missing = System.Reflection.Missing.Value;
                MSExcel.Application app = new MSExcel.ApplicationClass();
                app.Application.Workbooks.Add(true);
                MSExcel.Workbook book = (MSExcel.Workbook)app.ActiveWorkbook;
                MSExcel.Worksheet sheet = (MSExcel.Worksheet)book.ActiveSheet;
                sheet.Cells[1, 1] = "源数据站点名称记录";
                sheet.Cells[1, 2] = "匹配总数";
                for (int k = 0; k < 2; k++)
                {
                    sheet.Cells[k + 2, 1] = k;
                    sheet.Cells[k + 2, 2] = k;
                }
                string n = Server.MapPath("link.xls");
                   book.SaveCopyAs(n);
                 book.Close(false, missing, missing);
                
                 app.Quit();

    如果出现:

    无法嵌入互操作类型“Microsoft.Office.Interop.Excel.ApplicationClass”。请改用适用的接口
    解决办法是将引用的DLL:Microsoft.Office.Interop.Excel;的嵌入互操作类型改为false。

    转载于:https://www.cnblogs.com/wangzhenghua/archive/2013/05/08/3066951.html

    展开全文
  • 关于创建Excel表格所需要的索引库:NetOffice

    创建Excel

    创建Excel必要索引库:NetOffice 需版本对应

     			Excel.Application application = new Excel.Application();
    
                Excel.Workbook book = new Excel.Workbook();
    
                Excel.Worksheet sheet = (Excel.Worksheet)book.Worksheets[1];
    
                sheet.Cells[1, 1].Value = "测试";
    
                book.Save();
    
                application.Quit();
    
                application.Dispose();
    

    Excel保存对话框

     public static string OpenSaveDialog(Editor editor,Database db)
            {
                string directoryName = Path.GetDirectoryName(db.Filename);
    
                string fileName = Path.GetFileName(db.Filename);
    
                fileName = fileName.Substring(0, fileName.IndexOf('.'));
    
                PromptSaveFileOptions promptSaveFile = new PromptSaveFileOptions("保存Excel文件");
    
                promptSaveFile.DialogCaption = "保存Excel文件";
    
                promptSaveFile.Filter = "Excel 97-2003 工作薄(*.xls)|*.xls|Excel 工作簿(*.xlsx)|*.xlsx";
    
                promptSaveFile.FilterIndex = 1;
    
                promptSaveFile.InitialDirectory = directoryName;
    
                promptSaveFile.InitialFileName = fileName;
    
                PromptFileNameResult fileRes = editor.GetFileNameForSave(promptSaveFile);
    
                if(fileRes.Status == PromptStatus.OK)
                {
                    fileName = fileRes.StringResult;
                }
                else
                {
                    fileName = "";
                }
    
                return fileName;
            } 
    

    自定义数据

          public struct TextData
            {
                public string content;
                public double x;
                public double y;
                public double z;
            }
    

    将获取到的id数组数据转为自定义数据数组

     private TextData[] GetTextDatas(ObjectId[] ids,Database db)
            {
                TextData[] textDatas = new TextData[ids.Length];
                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    for (int i = 0; i < ids.Length; i++)
                    {
                        DBText dBText = ids[0].GetObject(OpenMode.ForRead) as DBText;
    
                        textDatas[i].content = dBText.TextString;
                        textDatas[i].x = dBText.Position.X;
                        textDatas[i].y = dBText.Position.Y; 
                        textDatas[i].z = dBText.Position.Z; ;
    
                    }
    
                    tr.Commit();
                }
    
                return textDatas;
            }
    

    保存数据到Excel表格

    private void SaveTextDatas(TextData[] textDatas,string fileName)
            {
                Excel.Application application = new Excel.Application(); //声明Excel表程序
    
                Excel.Workbook book = new Excel.Workbook(); //声明工作簿
    
                Excel.Worksheet sheet = (Excel.Worksheet)book.Worksheets[1]; //声明工作表
    
                //表头
                sheet.Cells[1, 1].Value = "测试1"; //写入数据
                sheet.Cells[1, 2].Value = "测试2"; //写入数据
                sheet.Cells[1, 3].Value = "测试3"; //写入数据
                sheet.Cells[1, 4].Value = "测试4"; //写入数据
                sheet.Cells[1, 5].Value = "测试5"; //写入数据
    
                for (int i = 0; i < textDatas.Length; i++)
                {
                    sheet.Cells[i + 2, 1].Value = i+1;
                    sheet.Cells[i + 2, 2].Value = textDatas[i].content;
                    sheet.Cells[i + 2, 3].Value = textDatas[i].x;
                    sheet.Cells[i + 2, 4].Value = textDatas[i].y;
                    sheet.Cells[i + 2, 5].Value = textDatas[i].z;
                }
    
                book.SaveAs(fileName); //保存
    
                application.Quit(); //退出Excel程序并销毁后台占用空间
    
                application.Dispose();
            }
        }
    

    读取Excel文件绘图

    先获取选择的Excel表格路径

    public static string OpenFileDialog(Editor editor, Database db)
            {
                string directoryName = Path.GetDirectoryName(db.Filename);
    
                string fileName = Path.GetFileName(db.Filename);
    
                fileName = fileName.Substring(0, fileName.IndexOf('.'));
    
                PromptOpenFileOptions promptSaveFile = new PromptOpenFileOptions("选择Excel文件");
    
                promptSaveFile.DialogCaption = "选择Excel文件";
    
                promptSaveFile.Filter = "Excel 97-2003 工作薄(*.xls)|*.xls|Excel 工作簿(*.xlsx)|*.xlsx";
    
                promptSaveFile.FilterIndex = 1;
    
                promptSaveFile.InitialDirectory = directoryName;
    
                promptSaveFile.InitialFileName = fileName;
    
                PromptFileNameResult fileRes = editor.GetFileNameForOpen(promptSaveFile);
    
                if (fileRes.Status == PromptStatus.OK)
                {
                    fileName = fileRes.StringResult;
                }
                else
                {
                    fileName = "";
                }
    
                return fileName;
            }
    

    再将表格中数据传递给自定义数据数组

      private List<TextData> GetDataForExcel(string filename)
            {
                List<TextData> textDatas = new List<TextData>();
    
                Excel.Application application = new Excel.Application(); //声明Excel表程序
    
                Excel.Workbook book = application.Workbooks.Open(filename);
    
                Excel.Worksheet sheet = (Excel.Worksheet)book.Worksheets[1]; //声明工作表
    
                int i = 2;
                while (sheet.Cells[i,2].Value != null && sheet.Cells[i, 2].Value.ToString() != "")
                {
                    TextData textData = new TextData();
    
                    textData.content = sheet.Cells[i, 2].Value.ToString();
                    textData.x = double.Parse (sheet.Cells[i, 3].Value.ToString());
                    textData.y = double.Parse(sheet.Cells[i, 4].Value.ToString()); 
                    textData.z = double.Parse(sheet.Cells[i, 5].Value.ToString());
                    textDatas.Add(textData);
                    i++;
                }
    
               
                application.Quit(); //退出Excel程序并销毁后台占用空间
    
                application.Dispose();
    
                return textDatas;
            }
    

    最后根据自定义数据数组进行绘图

    private void DrawText(Database db,List<TextData> textDatas)
            {
                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
    
                    BlockTable blockTable = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
    
                    BlockTableRecord blockTableRecord = (BlockTableRecord)tr.GetObject(blockTable[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
    
                    for (int i = 0; i < textDatas.Count; i++)
                    {
                        DBText dBText = new DBText();
    
                        //创建文字需要
                        Point3d s3 = new Point3d(textDatas[i].x, textDatas[i].y,textDatas[i].z);
    
                        dBText.Position = s3;
                        dBText.TextString = textDatas[i].content;
                        dBText.Height = 6;
                        //inserDimension.Width = 0;  //设置为0表示不会自动换行
                        dBText.HorizontalMode = TextHorizontalMode.TextCenter;
                        dBText.VerticalMode = TextVerticalMode.TextBase;
    
                        blockTableRecord.AppendEntity(dBText);
    
                        tr.AddNewlyCreatedDBObject(dBText, true);
                    }
                }
            }
    

    如何去调用这些方法?

     			Database db = HostApplicationServices.WorkingDatabase;
    
                Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
    
                string fileName = Tools.OpenFileDialog(ed, db);
    
                List<TextData> textDatas = new List<TextData>();
    
                if (fileName == "") return;
                     
                textDatas = GetDataForExcel(fileName);
    
                if (textDatas.Count == 0) return;
    
                DrawText(db, textDatas);
    

    好好加油!!!!!!!!!!Come on!!!!!!!!!

    展开全文
  • 创建Excel并写入内容 /// <summary> /// 创建Excel /// </summary> public void CrateExcel() { //文件保存路径 string path = "F:/text.xlsx"; FileInfo fileInfo = new F

    首先在NuGet下载EPPlus包

    在这里插入图片描述

    创建Excel并写入内容

      /// <summary>
            /// 创建Excel
            /// </summary>
            public void CrateExcel()
            {
                //文件保存路径
                string path = "F:/text.xlsx";
                FileInfo fileInfo = new FileInfo(path);
                using (ExcelPackage package = new ExcelPackage(fileInfo))
                {
                    //创建sheet1
                    ExcelWorksheet sheet = package.Workbook.Worksheets.Add("sheet1");
                    //设置基本样式
                    sheet.Cells.Style.Font.Name = "宋体";
                    sheet.Cells.Style.Font.Size = 11F;
                    sheet.Cells.Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                    sheet.Cells.Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
                    //设置指定单元格内容
                    sheet.Cells[1, 1].Value = "降板高度";
                    sheet.Cells[1, 2].Value = "生成填充区域";
                    sheet.Cells[1, 3].Value = "颜色R";
                    sheet.Cells[1, 4].Value = "颜色G";
                    sheet.Cells[1, 5].Value = "颜色B";
                    sheet.Cells[1, 6].Value = "RGB值";
                    sheet.Cells[1, 7].Value = "填充样式";
                    //设置行高
                    sheet.Row(1).Height = 19.5;
                    //设置区域背景颜色(设置背景颜色之前一定要设置PatternType)
                    sheet.Cells["A1:G1"].Style.Fill.PatternType = ExcelFillStyle.Solid;
                    sheet.Cells["A1:G1"].Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.FromArgb(232, 232, 232));
    
                    for (int i = 1; i <= 7; i++)
                    {
                        //设置单元格区域的边框
                        sheet.Cells[1, i].Style.Border.BorderAround(OfficeOpenXml.Style.ExcelBorderStyle.Thin, System.Drawing.Color.Black);
                    }
                    //保存
                    package.Save();
                }
            }
    

    EPPlus读取excel内容

     /// <summary>
            /// 读取Excel表格内容
            /// </summary>
            public void ReadExcel()
            {
                //文件路径
                string path = "F:/text.xlsx";
                FileStream fs = new FileStream(path, FileMode.Open);
                using (ExcelPackage package = new ExcelPackage(fs))
                {
                    ExcelWorksheet sheet = package.Workbook.Worksheets[1];
                    int n = sheet.Dimension.End.Row;
                    for (int i = 2; i <= n; i++)
                    {
                        var test = sheet.GetValue(i, 1).ToString();
                    }
                }
            }
    
    展开全文
  • C#创建excel

    千次阅读 2019-12-17 21:32:33
    小伙伴们在用C#操作excel的时候,可能需要通过代码去新建Excel,那么如何实现呢? 二、思路 1.组件:Epplus epplus组件的安装使用参考 在里面搜素Epplus即可 2.引用: using System.IO; using OfficeOpenXml; 3.代码...
  • 本文实例讲述了C#使用Ado.Net更新和添加数据到Excel表格的方法。分享给大家供大家参考。具体分析如下: 微软NET提供了一个交互的方法,通过使用ADO.NET与Microsoft Office程序。内置的OLEDB提供可以用来操纵Excel的...
  • C#读写Excel表格

    千次阅读 2022-04-18 14:36:31
    /// 读取表格 /// </summary> /// <param name="excelPath"></param> /// <returns></returns> static DataSet ExcelGetDataTable(string excelPath) { //处理格式..
  • 主要为大家详细介绍了C#创建Excel多级分组的方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
  • 第三步,创建Execl表格 //创建Excel Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application(); Workbook execlWB = excelApp.Workbooks.Add(System.Type.Missing...
  • ExcelFile.CreateEmptySheet("new");
  • c#操作读取和创建Excel

    2021-01-08 16:10:38
    使用c#Excel创建和读取,兼容了xls以及xlsx格式。Provider=Microsoft.ACE.OLEDB.12.0 Provider=Microsoft.Jet.OLEDB.4.0
  • /// 获取Excel表格里面的数据 /// </summary> /// <param name="filePath">Excel文件的路径</param> /// <param name="tabname">工作簿名称</param> /// <returns></...
  • 实例如下: private bool creatExcel(string xlsfile) ... Excel.ApplicationClass myExcel = new Excel.ApplicationClass(); Excel._Workbook xBk; //工作薄 Excel._Worksheet xSt; //工作Sheet xBk =
  • 主要为大家详细介绍了C#如何在Excel表格中插入、编辑和删除批注,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
  • 主要介绍了C#利用XML创建Excel文档的实现方法,需要的朋友可以参考下
  • 本文主要介绍一下c#来操作excel表格,主要介绍我使用的,我是使用第三方提供的函数库(NPOI)来进行excel的操作,而NPOI库函数在其官网下,我这里就不拿出来了。 1:NPOI库函数 NPOI库函数下载后,解压出来有...
  • 生成EXCEL文件是经常需要用到的功能,我们利用一些开源库可以很容易实现这个功能。 方法一:利用excellibrary,http://code.google.com/p/excellibrary/ excellibrary是国人写的开源组件,很容易使用,可惜...
  • 主要介绍了C#使用oledb读取excel表格内容到datatable的方法,涉及C#操作oledb及datatable的相关技巧,需要的朋友可以参考下
  • C#_EXCEL表格的导入和导出 1、安装NuGet程序包 2、添加命名空间 3、导入excel表格 4、导出excel表格 安装NuGet程序包 添加命名空间 导入excel表格 导入内容 public string [,] table_data = new string [10...
  • 代码如下://创建excelobject missing = System.Reflection.Missing.Value;Excel.Application app = new Excel.Application();app.Application.Workbooks.Add(true);Excel.Workbook book = (Excel.Workbook)app....

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 8,474
精华内容 3,389
关键字:

c#创建excel表格

c# 订阅