C++生成任意阶螺旋方阵输出到Excel

合集下载

C 将数据导出到 Excel表

C 将数据导出到 Excel表
这里我们利用了 ContentType 属性,它默认的属性为 text/html,这时将输出为超文本 ,即我们常见的网页格式到客户端,如果改为 ms-excel 将将输出 excel 格式,也就是说 以电子表格的格式输出到客户端,这时浏览器将提示你下载保存。ContentType 的属性 还包括:image/JPEG;text/HTML;image/GIF;vnd.ms-excel/msword 。同理,我们 也可以输出(导出)图片、word 文档等。下面的方法,也均用了这个属性。
此法将 html 中所有的内容,如按钮,表格,图片等全部输出到 xecl 中。
Response.Clear(); Response.Buffer= true; Response.AppendHeader("Content-Disposition","attachment;filename="+DateTime.Now. ToString("yyyyMMdd")+".xls"); Response.ContentEncoding=System.Text.Encoding.UTF8; Response.ContentType = "application/vnd.ms-excel"; this.EnableViewState = false;
一、 中导出 Execl 的方法:
在 中导出 Execl 有两种方法,一种是将导出的文件存放在服务器某个文件夹下面 ,然后将文件地址输出在浏览器上;一种是将文件直接将文件输出流写给浏览器。在 Res ponse 输出时,t 分隔的数据,导出 execl 时,等价于分列,n 等价于换行。 1、将整个 html 全部输出 execl

C#导出数据到EXCEL方法谈(附实例源码和超级无敌详细讲解)

C#导出数据到EXCEL方法谈(附实例源码和超级无敌详细讲解)

C#导出数据到EXCEL方法谈(附实例源码和详细讲解)如果你耐心仔细看完本文,相信以后再遇到导出EXCLE操作的时候你会很顺手觉得SO EASY,主要给新手朋友们看的,老鸟可以直接飘过了,花了一晚上的时间写的很辛苦,如果觉得对你有帮助烦请留言支持一下,我会写更多基础的原创内容来回报大家。

C#导出数据到EXCEL表格是个老生常谈的问题了,写这篇文章主要是给和我一样的新手朋友提供两种导出EXCEL的方法并探讨一下导出的效率问题,本文中的代码直接就可用,其中部分代码参考其他的代码并做了修改,抛砖引玉,希望大家一起探讨,如有不对的地方还请大家多多包涵并指出来,我也是个新手,出错也是难免的。

首先先总结下自己知道的导出EXCEL表格的方法,大致有以下几种,有疏漏的请大家补充。

1.数据逐条逐条的写入EXCEL2.通过OLEDB把EXCEL做为数据源来写3.通过RANGE范围写入多行多列内存数据到EXCEL4.利用系统剪贴板写入EXCEL好了,我想这些方法已经足够完成我们要实现的功能了,方法不在多,在精,不是么?以上4中方法都可以实现导出EXCEL,方法1为最基础的方法,意思就是效率可能不是太高,当遇到数据量过大时所要付出的时间也是巨大的,后面3种方法都是第一种的衍生,在第一种方法效率低下的基础上改进的,这里主要就是一个效率问题了,当然如果你数据量都很小,我想4种方法就代码量和复杂程度来说第1种基本方法就可以了,或当你的硬件非常牛逼了,那再差的方法也可以高效的完成也没有探讨的实际意义了,呵呵说远了,本文主要是在不考虑硬件或同等硬件条件下单从软件角度出发探讨较好的解决方案。

此项目代码已打包在附件中,几乎注释的无微不至,在配合本文中我唐僧般的娓娓道来(靠,谁丢臭鸡蛋砸俺了),相信即使刚入门C#的朋友也能看得懂了吧,大家可以自行下载,代码中演示了两种方法,上述的方法1和方法3,我想足够了,方法3的效率应该是四种中最高的了,其他两种有兴趣的朋友自己实现下哈(方法2在我的程序中也有用到一些,看完你就知道了),程序如下图所示,先加载一个EXCEL表格进DATAGRIDVIEW作为数据源,然后两种方法导出EXCEL,配上一个计数功能给大家直观的看到导出的耗时,大家可以准备个几万行和十多行的两个EXCEL作为数据源来测试,也可以用我打包里的XLS来测试下。

经典三种C#导入导出到EXCEL的方法(C#开发人员必备)

经典三种C#导入导出到EXCEL的方法(C#开发人员必备)

C#导入导出EXCEL------------阿秋笔记add by 2011-3-24注:本文中的所有案例全部测试通过,请放心使用!三大功能:1,导入:把EXCEL文件导入到对应的数据库表中2,导出:(1)把HTML页面直接导出到EXCEL;(2)把DataTable对象导出到EXCEL 环境:VS2005 + SQL SERVER 2005 Language:C#1,导入步骤:上传EXCEL文件,保存到服务器某一个文件夹下,然后解析的DataTable中,在分解插入到数据库表中实现代码:(1)前台,Default.aspx 放入一个上传控件FileUpload + 按钮控件Button代码:<asp:FileUpload ID="FU"runat="server"Width="595px"/><asp:Button ID="btnUpload"runat="server"Text="上传"OnClick="btnUpload_Click"/> (2)后台Default.asp.cs代码:-----按钮单击事件btnUpload_Clickprotected void btnUpload_Click(object sender, EventArgs e){if (this.FU.PostedFile == null || this.FU.PostedFile.FileName == "") //判断是否选择上载文件{this.RegisterStartupScript("1","alert('请选择上传的数据文件!');");return;}string m_ExtName =Path.GetExtension(TrimHtml(Path.GetFileName(this.FU.PostedFile.FileName))).ToLower();if ((m_ExtName.Replace(".", "") != "xls")){this.RegisterStartupScript("2","alert('请上传Execl类型文件!');");return;}string newname = DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss") + m_ExtName;FU.PostedFile.SaveAs(Server.MapPath("~/xx/"+newname));string fPath = Request.PhysicalApplicationPath + "xx/" + newname;fPath = fPath.Replace("\\", "/");DataTable dt = ExcelToDS(fPath, "LAWUSER");bool IsSuccessful = true;string _errorRow = "";foreach (DataRow row in dt.Rows){if (row["姓名"].ToString().Trim().Equals("")){continue;}string id = row["编号"].ToString();string name = row["姓名"].ToString();string tel = row["联系电话"].ToString();string sql = "insert into AA values('" + id + "','" + name + "','" + tel + "')";try{int i = SqlHelper1.ExecuteNonQuery(sql);if (i > 0){this.RegisterStartupScript("4", "susccessfully");}else{ this.RegisterStartupScript("4","插入错误"); }}catch (Exception ex){this.RegisterStartupScript("3","alert('"+ex.Message+"');");}}}-----函数ExcelToDS,这里的ExtandName是指EXCEL中对应的Sheet1修改后的名称private DataTable ExcelToDS(string Path, string ExtandName){string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+ Path + ";"+ "Extended Properties='Excel 8.0;'";OleDbConnection conn = new OleDbConnection(strConn);conn.Open();string strExcel = "";OleDbDataAdapter myCommand = null;DataSet ds = null;strExcel = "select * from [" + ExtandName + "$]";myCommand = new OleDbDataAdapter(strExcel, strConn);ds = new DataSet();myCommand.Fill(ds, "table1");return ds.Tables[0];}-----对字符串操作函数TrimHtmlprivate string TrimHtml(string str){return str.Replace("&", "").Replace("<", "").Replace("'", "").Replace("\"","").Replace("\\", "");}(3)数据库表格式:CREATE TABLE [dbo].[AA]([id] [int] NOT NULL,[name] [varchar](50)COLLATE Chinese_PRC_CI_AS NULL,[tel] [varchar](50)COLLATE Chinese_PRC_CI_AS NULL,CONSTRAINT [PK_AA] PRIMARY KEY CLUSTERED([id] ASC)WITH(PAD_INDEX =OFF, STATISTICS_NORECOMPUTE =OFF, IGNORE_DUP_KEY =OFF, ALLOW_ROW_LOCKS =ON, ALLOW_PAGE_LOCKS =ON)ON [PRIMARY])ON [PRIMARY]注意表列与DataTable中的数据一一对应即可2,导出,将HTML导出到EXCEL,注:我这里是后台实现导出,也有用JS脚本导出的。

用C++导出到Excel文档

用C++导出到Excel文档
中,应用人员可以很方便地进行调用。
设置对象属性:Variant OlePropertySet(属性名,参数……);
获得对象属性:void OlePropertyGet(属性名,参数……);
调用对象方法:1) Variant OleFunction(函数名,参数……);
Eh1-> Columns-> Items[i]-> Field-> AsString.c_str());
sheet.OlePropertyGet("Cells",1,1).OlePropertyGet("Font").OlePropertySet("Nam
e","隶书");
sheet.OlePropertyGet("Cells",2,3).OlePropertyGet("Font").OlePropertySe
ex.OlePropertyGet("workbooks").OleFunction("Add") //默认工作簿
ex.OlePropertyGet("workbooks").OleFunction("Add",1) //单工作表
ex.OlePropertyGet("workbooks").OleFunction("Add",2) //图表
my_worksheet.OlePropertyGet("Rows",2).OleProcedure("Insert");//插入一行
//根据DBGrid的表头输出Excel表头

螺旋矩阵(C语言)

螺旋矩阵(C语言)

螺旋矩阵问题(C语言实现)问题:输入矩阵的行列数,生成螺旋矩阵,比如输入5 6,生产矩阵:#include <stdio.h>#define M 100void RataterArray(int array[M][M],int rows,int cols){int regcount=rows%2==0?rows/2:(rows+1)/2;//regcount为矩形个数int seedNum=1;//seedNum初值for(int i=0;i<regcount;i++)//为每层矩形赋值{for(int row=0;row<rows;row++){for(int col=0;col<cols;col++){//矩形的上边横线if(row==i&&array[row][col]==-1){array[row][col]=seedNum-i+col;}//矩形的右边横线if(col==(cols-i-1)&&array[row][col]==-1){array[row][col]=seedNum+(rows-2*i)+(cols-2*i)-2-(rows-i-1-row);}//矩形的下边横线if(row==(rows-1-i)&&array[row][col]==-1){array[row][col]=seedNum+(rows-2*i)+(cols-2*i)-2+(cols-i-1-col);}//矩形左边竖线if(col==i&&array[row][col]==-1){array[row][col]=seedNum+(rows-2*i)+(cols-2*i)-2+(cols-i*2)-1+(rows-i-1-row);}}}seedNum=(rows-2*i+cols-2*i)*2-4+seedNum;//矩形的尾值作为内含矩形的seedNum初始值}}void main(){int array[M][M];//分别为数组的行和列int rows,cols;printf("请输入螺旋数组的行数和列数:");scanf("%d %d",&rows,&cols);//初始化数组为-1for(int i=0;i<rows;i++){for(int j=0;j<cols;j++){array[i][j]=-1;}}//螺旋数组赋值函数RataterArray(array,rows,cols);printf("打印螺旋数值如下:\n");for(i=0;i<rows;i++){for(int j=0;j<cols;j++){printf("%4d",array[i][j]);}printf("\n");}}运行效果:。

C语言螺旋方阵解析

C语言螺旋方阵解析

C语言螺旋方阵解析3螺旋方阵题目:Input Height N, printf such pattern:1 2 3 4 516 17 18 19 615 24 25 20 714 23 22 21 813 12 11 10 9第一种解法:是用等差数列解题。

算法:1 2 3 4 516 17 18 19 615 24 25 20 714 23 22 21 813 12 11 10 9定义行i列j。

从外向内分层,一圈一层。

定义r:(r&gt;=1)当前圈为第几圈。

定义N:图形高度定义l:当前圈边长ll(1)=N-1l(r)=N-2*(r-1)-1设当前圈左上角为开始。

定义d:当前行的方向(上边为0右边为1下边为2左边为3)定义pl:当前圈当前边距角的长度(向数字小的方向)定义a:当前圈共有多少个数字a(r)=4*l(r)=4*(N-2*(r-1))-4公差为-8从最外圈到当前圈求和:s(r)=a(1)*r-r*(r-1)/2*(-8)定义b:本圈第一个数字b(r)=s(r-1)+1=a(1)*(r-1)-(r-1)*(r-2)/2*(-8)+1开始计算:求r: r=min(i,N-j+1,N-i+1,j)求d: d为(i,N-j+1,N-i+1,j)与r对应,如r如第1个值,则d为第一个值... 求pl: p=(j-r,i-r,N-j+1-r,N-i+1-r)与r对应,如r如第1个值,则d为第一个值...当前数值b+l*d+plCommented by Wang Rui程序如下:main( ){ int i,j,r,l,b,d,pl,N;printf(&quot;Input Height:&quot;); /*输入高度*/ scanf(&quot;%d&quot;,&amp;N);for (i=1;i&lt;=N;i++){ for (j=1;j&lt;=N;j++) /*定位到第i行第j列*/ { r=i;d=0;pl=j-r;if (r&gt;N-j+1) {r=N-j+1;d=1;pl=i-r;}if (r&gt;N-i+1) {r=N-i+1;d=2;pl=N-j+1-r;}if (r&gt;j) {r=j;d=3;pl=N-i+1-r;}/*找出圈数,边的位置,在边上的位置*/l=N-2*(r-1)-1;/*边长*/b=(4*N-4)*(r-1)-4*(r-1)*(r-2)+1;/*本圈开始的数字*/printf(&quot;%4d&quot;,b+l*d+pl);/*打印数字*/ }printf(&quot;\n&quot;);}}第二种解法:这是用几何方法解的。

C#导出Excel

C#导出Excel

首先你需要添加引用Microsoft Excel 11.0 Object Library添加方法:选择项目->引用->右击“添加引用”->选择COM 找到上面组件—>点击“确定”。

其次添加Microsoft.Office.Interop.Excel引用添加方法:选择项目->引用->右击“添加引用”->浏览C:\Windows\assembly\GAC\Microsoft.Office.Interop.Excel\12.0.0.0__71e9bce111e9429c\Micros oft.Office.Interop.Excel.dll/// <summary>/// 导出到EXCEL/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void tsExportToExcel_Click(object sender, EventArgs e){SaveFileDialog dialog = new SaveFileDialog();dialog.Filter = "Excel(*.xls)|*.xls|All Files(*.*)|*.*";dialog.FileName = "CallHistory.xls";if (dialog.ShowDialog() == DialogResult.OK){Microsoft.Office.Interop.Excel.ApplicationxlApp = new Microsoft.Office.Interop.Excel.Application();object missing = System.Reflection.Missing.Value;try{if (xlApp == null){MessageBox.Show("无法创建Excel对象,可能您的机子未安装Excel");return;}Microsoft.Office.Interop.Excel.WorkbooksxlBooks = xlApp.Workbooks;Microsoft.Office.Interop.Excel.WorkbookxlBook = xlBooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);Microsoft.Office.Interop.Excel.WorksheetxlSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlBook.Worksheets[1];Microsoft.Office.Interop.Excel.Range range = null;//****** 抬头******************************************************************************* **range = xlSheet.get_Range("A1", "G1");range.Merge(Missing.Value); // 合并单元格range.Columns.AutoFit(); // 设置列宽为自动适应// 设置单元格左边框加粗range.Borders[XlBordersIndex.xlEdgeLeft].Weight = XlBorderWeight.xlThick;// 设置单元格右边框加粗range.Borders[XlBordersIndex.xlEdgeRight].Weight = XlBorderWeight.xlThick;range.HorizontalAlignment = XlHAlign.xlHAlignCenter;// 设置单元格水平居中range.Value2 = "G1 通话记录清单";range.Font.Size = 18; // 设置字体大小range.Font.ColorIndex = 5; // 设置字体颜色//range.Interior.ColorIndex = 6; // 设置单元格背景色range.RowHeight = 25; // 设置行高range.ColumnWidth = 20; // 设置列宽xlSheet.Cells[2, 1] = "时间";xlSheet.Cells[2, 2] = "电话号码";xlSheet.Cells[2, 3] = "联系人";xlSheet.Cells[2, 4] = "类型";xlSheet.Cells[2, 5] = "通话时长";xlSheet.Cells[2, 6] = "分组";xlSheet.Cells[2, 7] = "归属地";introwIndex = 3;//这个用来标记数据有多少行位置//-----------------------设置单元格--------------------------------------------------------------------------------range = xlSheet.get_Range(xlSheet.Cells[3, 7], xlSheet.Cells[rowIndex + this.lvwList.Items.Count, 7]);//归属地range.HorizontalAlignment = XlHAlign.xlHAlignLeft;// 设置单元格水平居左range.NumberFormatLocal = "@";//文本格式range.ColumnWidth = 30;range = xlSheet.get_Range(xlSheet.Cells[3, 6], xlSheet.Cells[rowIndex + this.lvwList.Items.Count, 6]);//分组range.HorizontalAlignment = XlHAlign.xlHAlignLeft;// 设置单元格水平居左range.NumberFormatLocal = "@";//文本格式range.ColumnWidth = 12;range = xlSheet.get_Range(xlSheet.Cells[3, 5], xlSheet.Cells[rowIndex +this.lvwList.Items.Count, 5]);//通话时长range.HorizontalAlignment = XlHAlign.xlHAlignLeft;// 设置单元格水平居左range.NumberFormatLocal = "@";//文本格式range.ColumnWidth = 12;range = xlSheet.get_Range(xlSheet.Cells[3, 4], xlSheet.Cells[rowIndex + this.lvwList.Items.Count, 4]); //类型range.HorizontalAlignment = XlHAlign.xlHAlignLeft;// 设置单元格水平居左range.ColumnWidth = 12;range = xlSheet.get_Range(xlSheet.Cells[3, 3], xlSheet.Cells[rowIndex + this.lvwList.Items.Count, 3]); //联系人range.HorizontalAlignment = XlHAlign.xlHAlignLeft;// 设置单元格水平居左range.ColumnWidth = 18;range = xlSheet.get_Range(xlSheet.Cells[3, 2], xlSheet.Cells[rowIndex + this.lvwList.Items.Count, 2]); //电话号码range.HorizontalAlignment = XlHAlign.xlHAlignLeft;// 设置单元格水平居左range.NumberFormatLocal = "@";//文本格式range.ColumnWidth = 18;range = xlSheet.get_Range(xlSheet.Cells[3, 1], xlSheet.Cells[rowIndex + this.lvwList.Items.Count, 1]); //时间range.NumberFormatLocal = "yyyy-MM-ddHH:mm";//日期格式range.ColumnWidth = 18;//-----------------------设置单元格--------------------------------------------------------------------------------//标题栏range = xlSheet.get_Range(xlSheet.Cells[2, 1], xlSheet.Cells[2, 7]);range.Interior.ColorIndex = 45;//设置标题背景色为浅橙色range.Font.Bold = true;//标题字体加粗foreach (ListViewItemobjItem in this.lvwList.Items){xlSheet.Cells[rowIndex, 1] = Convert.ToDateTime(objItem.Text);xlSheet.Cells[rowIndex, 2] = objItem.SubItems[1].Text;xlSheet.Cells[rowIndex, 3] = objItem.SubItems[2].Text;xlSheet.Cells[rowIndex, 4] = objItem.SubItems[3].Text;xlSheet.Cells[rowIndex, 5] = objItem.SubItems[4].Text;xlSheet.Cells[rowIndex, 6] = objItem.SubItems[5].Text;xlSheet.Cells[rowIndex, 7] = objItem.SubItems[6].Text;rowIndex += 1;}//数据区域range = xlSheet.get_Range(xlSheet.Cells[2, 1], xlSheet.Cells[rowIndex, 7]);range.Borders.LineStyle = 1;range.Font.Size = 10;range=xlSheet.get_Range(xlSheet.Cells[rowIndex,1],xlSheet.Cells[rowIndex, 7]);range.Merge(Missing.Value); // 合并单元格// range.Borders[XlBordersIndex.xlEdgeLeft].Weight = XlBorderWeight.xlThick;// 设置单元格右边框加粗// range.Borders[XlBordersIndex.xlEdgeRight].Weight = XlBorderWeight.xlThick;range.RowHeight = 20;range.Value2 = "汇出时间: " +DateTime.Now.ToString("yyyy-MM-ddHH:mm:ss");range.HorizontalAlignment = XlHAlign.xlHAlignRight;// 设置单元格水平居中//***** 格式设定******************************************************************************if (xlSheet != null){xlSheet.SaveAs(dialog.FileName, missing, missing, missing, missing, missing, missing, missing, missing, missing);xlApp.Visible = true;}}catch (Exception){xlApp.Quit();throw;}}KillAllExcel();}}///操作完成结束进程private static void KillAllExcel(){List<Process>excelProcess = GetExcelProcesses(); for (inti = 0; i<excelProcess.Count; i++){excelProcess[i].Kill();}}/// <summary>/// 获得所有的Excel进程/// </summary>/// <returns>所有的Excel进程</returns>private static List<Process>GetExcelProcesses(){Process[] processes = Process.GetProcesses();List<Process>excelProcesses = new List<Process>();for (inti = 0; i<processes.Length; i++){if (processes[i].ProcessName.ToUpper() == "EXCEL") excelProcesses.Add(processes[i]);}returnexcelProcesses;}。

c#导出excel的三种方式

c#导出excel的三种方式

c#导出excel的三种⽅式第⼀种:流导出SaveFileDialog exe = new SaveFileDialog();exe.Filter = "Execl files (*.xls)|*.xls";exe.FilterIndex = 0;exe.RestoreDirectory = true;//exe.CreatePrompt = true;exe.Title = "Export Excel File";exe.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);exe.FileName = string.Format("{0}_{1}", DateTime.Now.ToString("yyyy-MM-dd HH时mm分ss秒"), "导出"); DialogResult dr = exe.ShowDialog();if (dr != DialogResult.OK){return;} Stream ms;ms = exe.OpenFile();StreamWriter sw = new StreamWriter(ms, System.Text.Encoding.GetEncoding(-0));string str = "";try{for (int i = 0; i < dtb.Columns.Count; i++){if (i > 0){str += "\t";}str += dtb.Columns[i].HeaderText;}sw.WriteLine(str);for (int j = 0; j < dtb.Rows.Count; j++){string temp = "";for (int k = 0; k < dtb.Columns.Count; k++){if (k > 0){temp += "\t";}string cell = dtb.Rows[j].Cells[k].Value.ToString();cell = cell.Replace("", "").Replace("\r", "").Replace("\n", "").Replace("\r\n", "");temp += cell;}sw.WriteLine(temp);}sw.Close();ms.Close();}catch (Exception ex){MessageBox.Show(ex.Message);return;}finally{sw.Close();ms.Close();}第⼆种:使⽤ Microsoft.Office.Interop.Excel.dllMicrosoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();if (xlApp == null){MessageBox.Show("⽆法创建Excel对象,可能您的机⼦未安装Excel");return;}try{Workbooks wbs = xlApp.Workbooks;Workbook wb = wbs.Add(XlWBATemplate.xlWBATWorksheet);Worksheet ws = (Worksheet)wb.Worksheets[1];Range range = xlApp.Range[ws.Cells[1, 1], ws.Cells[1, colcount]];range.Font.Size = 10;range.Font.Bold = true;range.Interior.ColorIndex = 15;range.HorizontalAlignment = Constants.xlCenter;object[,] obj = new object[rowcount + 1, colcount];foreach (DataGridViewColumn col in dtb.Columns){obj[rowindex, colindex++] = col.HeaderText;}for (rowindex = 1; rowindex < rowcount + 1; rowindex++){for (colindex = 0; colindex < colcount; colindex++){obj[rowindex, colindex] = "'" + dtb[colindex, rowindex - 1].Value;}System.Windows.Forms.Application.DoEvents();}range = ws.Range[xlApp.Cells[1, 1], xlApp.Cells[rowcount + 1, colcount]];range.Value2 = obj;wb.Saved = true;wb.SaveCopyAs(exe.FileName);//for (int i = 0; i < dtb.ColumnCount; i++)//{// if (dtb.Columns[i].Visible)// {// colindex++;// ws.Cells[1, colindex] = dtb.Columns[i].HeaderText;// }//}//for (int r = 0; r < dtb.Rows.Count; r++)//{// colindex = 0;// for (int i = 0; i < dtb.ColumnCount; i++)// {// if (dtb.Columns[i].Visible)// {// colindex++;// ws.Cells[r + 2, colindex] = "'" + dtb.Rows[r].Cells[i].Value;// }// }//}//System.Windows.Forms.Application.DoEvents();//wb.SaveAs(exe.FileName);}catch (Exception ex){MessageBox.Show("导出⽂件时出错,⽂件可能正被打开!\n" + ex.Message);}finally{xlApp.Quit();GC.Collect();}这两种⽅法导出 .xlsx 格式的 Excel ⽂件时,没办法打开。

c导出数据到excel文件

c导出数据到excel文件

C#导出数据到Excel文件/// 导出到Excel类,项目需引用Microsodt.Office.Interop.Excel,/// 类文件需using System.Data与System.Windows.Forms命名空间/// /summarypublic class CToExcel/// summary/// 导出到Excel/// /summary/// param name= fileName 默认文件名/param/// param name= listView 数据源,一个页面上的ListView控件/param/// param name= titleRowCount 标题占据的行数,为0表示无标题/parampublic void ExportExcel(string fileName, System.Windows.Forms.ListView listView,int titleRowCount)string saveFileName =//bool fileSaved = false;SaveFileDialog saveDialog = new SaveFileDialog();saveDialog.DefaultExt = xlssaveDialog.Filter = Excel文件|*.xlssaveDialog.FileName = fileName;saveDialog.ShowDialog();saveFileName = saveDialog.FileName;if (saveFileName.IndexOf( : ) 0) return; //被点了取消Microsoft.Office.Interop.Excel.Application xlApp;xlApp = new Microsoft.Office.Interop.Excel.Application();catch (Exception)MessageBox.Show( 无法创建Excel对象,可能您的机子未安装Excelreturn;finallyMicrosoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBA Template.xlWBA TWorksheet);Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];//取得sheet1//写Titleif(titleRowCount!=0)MergeCells(worksheet, 1, 1, titleRowCount, listView.Columns.Count, listView.Tag.ToString()); //写入列标题for (int i = 0; i = listV iew.Columns.Count - 1; i++)worksheet.Cells[titleRowCount+1, i + 1] = listView.Columns[i].Text;//写入数值for (int r = 0; r = listView.Items.Count - 1; r++)for (int i = 0; i = listV iew.Columns.Count - 1; i++)worksheet.Cells[r + titleRowCount+2, i + 1] = listView.Items[r].SubItems[i].Text;System.Windows.Forms.Application.DoEvents();worksheet.Columns.EntireColumn.AutoFit();//列宽自适应//if (Microsoft.Office.Interop.cmbxType.Text != Notification )// Excel.Range rg = worksheet.get_Range(worksheet.Cells[2, 2], worksheet.Cells[ds.Tables[0].Rows.Count + 1, 2]);// rg.NumberFormat = 00000000if (saveFileName != )workbook.Saved = true;workbook.SaveCopyAs(saveFileName);//fileSaved = true;catch (Exception ex)//fileSaved = false;MessageBox.Show( 导出文件时出错,文件可能正被打开!n + ex.Message);//else// fileSaved = false;xlApp.Quit();GC.Collect();//强行销毁// if (fileSaved System.IO.File.Exists(saveFileName)) System.Diagnostics.Process.Start(saveFileName); //打开EXCELMessageBox.Show(fileName + 导出到Excel成功, 提示, MessageBoxButtons.OK);/// summary/// DataTable导出到Excel/// /summary/// param name= fileName 默认的文件名/param/// param name= dataTable 数据源,一个DataTable数据表/param/// param name= titleRowCount 标题占据的行数,为0则表示无标题/parampublic void ExportExcel(string fileName,System.Data.DataTable dataTable,int titleRowCount)string saveFileName =//bool fileSaved = false;SaveFileDialog saveDialog = new SaveFileDialog();saveDialog.DefaultExt = xlssaveDialog.Filter = Excel文件|*.xlssaveDialog.FileName = fileName;saveDialog.ShowDialog();saveFileName = saveDialog.FileName;if (saveFileName.IndexOf( : ) 0) return; //被点了取消Microsoft.Office.Interop.Excel.Application xlApp;xlApp = new Microsoft.Office.Interop.Excel.Application();catch (Exception)MessageBox.Show( 无法创建Excel对象,可能您的机子未安装Excelreturn;finallyMicrosoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBA Template.xlWBA TWorksheet);Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];//取得sheet1//写Titleif(titleRowCount!=0)MergeCells(worksheet, 1, 1, titleRowCount, dataTable.Columns.Count, dataTable.TableName);//写入列标题for (int i = 0; i = dataTable.Columns.Count - 1; i++)worksheet.Cells[titleRowCount+1, i + 1] = dataTable.Columns[i].ColumnName;//写入数值for (int r = 0; r = dataTable.Rows.Count - 1; r++)for (int i = 0; i = dataTable.Columns.Count - 1; i++)worksheet.Cells[r +titleRowCount+ 2, i + 1] = dataTable.Rows[r][i].ToString();System.Windows.Forms.Application.DoEvents();worksheet.Columns.EntireColumn.AutoFit();//列宽自适应//if (Microsoft.Office.Interop.cmbxType.Text != Notification )// Excel.Range rg = worksheet.get_Range(worksheet.Cells[2, 2], worksheet.Cells[ds.Tables[0].Rows.Count + 1, 2]);// rg.NumberFormat = 00000000if (saveFileName != )workbook.Saved = true;workbook.SaveCopyAs(saveFileName);//fileSaved = true;catch (Exception ex)//fileSaved = false;MessageBox.Show( 导出文件时出错,文件可能正被打开!n + ex.Message);//else// fileSaved = false;xlApp.Quit();GC.Collect();//强行销毁// if (fileSaved System.IO.File.Exists(saveFileName)) System.Diagnostics.Process.Start(saveFileName); //打开EXCELMessageBox.Show(fileName + 导出到Excel成功, 提示, MessageBoxButtons.OK);/// 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的值/parampublic 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(workSheet.Cells[beginRowIndex, beginColumnIndex], workSheet.Cells[endRowIndex, endColumnIndex]);range.ClearContents(); //先把Range内容清除,合并才不会出错range.MergeCells = true;range.V alue2 = text;range.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;range.V erticalAlignment = Microsoft.Office.Interop.Excel.XlV Align.xlV AlignCenter;}。

C#导出EXCEL方法总结

C#导出EXCEL方法总结

C#导出EXCEL⽅法总结下⾯介绍下我根据⽹上学习C#中导出EXCEL的⼏种⽅法:⼀、导出Excel1.将整个html全部输出到Excel此⽅法会将html中所有的内容,如按钮、表格、图⽚等全部输出View Code2.将DataGrid控件中的数据导出到Excel(也可以是其他控件)此⽅法若使⽤分页,则导出当前页DataGrid中显⽰的信息。

View Code⽤法DGToExcel(datagrid1);3.将DataSet中的数据导出到ExcelView Code以ms-excel的格式response到http流,参数ds为填充有数据表的DataSet,⽂件名是全名,包括后缀名,如Excel2006.xls。

4.将dataview导出到ExcelView Code⼆、winform中导出Excel的⽅法1.⽅法View Code2.⽅法View Code3.从DataGridView⾥导出按 Ctrl+C 复制代码按 Ctrl+C 复制代码4.把Excel数据读到DataSet⾥View Code三、字符串导出⽅法1.通⽤导出Excel的⽅法View Code2.给个例⼦View Code3.学习下他⼈的如果你仅仅只有 Web Forms背景转⽽学习 MVC的,我想你的第⼀个经历或许是那些曾经让你的编程变得愉悦⽆⽐的服务端控件都驾鹤西去了.FileUpload就是其中⼀个,⽽这个控件的缺席给我们带来⼀些⼩问题。

这篇⽂章主要说如何在 MVC中上传⽂件,然后如何再从服务器中把上传过的⽂件下载下来.在Web Forms中,当你把⼀个FileUpload控件拖到设计器中,你或许没有注意到在⽣成的HTML中会在form标签中加⼊⼀条额外属性enctype="multipart/form-data". ⽽FileUpload控件本⾝会⽣成为<input type=”file” />,在MVC的view⾥,有许多种⽅法可以做到同样效果,第⼀种的HTML如下:<form action="/" method="post" enctype="multipart/form-data"><input type="file" name="FileUpload1" /><br /><input type="submit" name="Submit" id="Submit" value="Upload" /></form>注意form标签已经包括了enctype标签,⽽method属性则设为”post”,这样设置并不多于因为默认的提交时通过HTTP get⽅式进⾏的。

C语言螺旋方阵解析

C语言螺旋方阵解析

3螺旋方阵‎‎‎‎‎‎‎‎‎题目‎:Inpu‎t Hei‎g ht N‎, pri‎n tf s‎u ch p‎a tter‎n:‎ 1 ‎2 ‎3 4‎ 5 ‎16‎ 17 ‎18 ‎19 ‎6‎15 2‎4 25‎ 20 ‎ 7‎ 14 ‎23 ‎22 2‎1 8‎1‎3 12‎ 11 ‎10 ‎9‎第一种解法‎:是用等差‎数列解题。

‎算法:‎‎1 2‎ 3 ‎ 4 ‎5‎16 ‎17 1‎8 19‎ 6 ‎15‎ 24 ‎25 ‎20 ‎7‎14 2‎3 22‎ 21 ‎ 8‎ 13 ‎12 ‎11 1‎0 9‎定义行‎i列j。

从‎外向内分层‎,一圈一层‎。

定义r:‎(r>=1‎)当前圈为‎第几圈。

‎定义N:‎图形高度‎定义l:‎当前圈边长‎ll(‎1)=N-‎1l(‎r)=N-‎2*(r-‎1)-1 ‎设当前圈‎左上角为开‎始。

定义d‎:当前行的‎方向(上边‎为0右边为‎1下边为2‎左边为3)‎定义p‎l:当前圈‎当前边距角‎的长度(向‎数字小的方‎向)定‎义a:当前‎圈共有多少‎个数字‎a(r)=‎4*l(r‎)=4*(‎N-2*(‎r-1))‎-4公‎差为-8 ‎从最外圈‎到当前圈求‎和:s(r‎)=a(1‎)*r-r‎*(r-1‎)/2*(‎-8)‎定义b:本‎圈第一个数‎字b(‎r)=s(‎r-1)+‎1‎ =a(‎1)*(r‎-1)-(‎r-1)*‎(r-2)‎/2*(-‎8)+1 ‎开始计算‎:求r‎: r=‎m in(i‎,N-j+‎1,N-i‎+1,j)‎求d:‎ d为(‎i,N-j‎+1,N-‎i+1,j‎)与r对应‎,如r如第‎1个值,则‎d为第一个‎值... ‎求pl:‎ p=‎(j-r,‎i-r,N‎-j+1-‎r,N-i‎+1-r)‎与r对应,‎如r如第1‎个值,则d‎为第一个值‎...‎当前数值b‎+l*d+‎p lC‎o mmen‎t ed b‎y Wan‎g Rui‎程序‎如下:‎m ain(‎){‎int ‎i,j,r‎,l,b,‎d,pl,‎N;p‎r intf‎("Inp‎u t He‎i ght:‎"); /‎*输入高度‎*/s‎c anf(‎"%d",‎&N); ‎for ‎(i=1;‎i<=N;‎i++) ‎{ fo‎r (j=‎1;j<=‎N;j++‎) /*定‎位到第i行‎第j列*/‎{ r‎=i;d=‎0;pl=‎j-r; ‎if (‎r>N-j‎+1) {‎r=N-j‎+1;d=‎1;pl=‎i-r;}‎if ‎(r>N-‎i+1) ‎{r=N-‎i+1;d‎=2;pl‎=N-j+‎1-r;}‎if ‎(r>j)‎{r=j‎;d=3;‎p l=N-‎i+1-r‎;}/‎*找出圈数‎,边的位置‎,在边上的‎位置*/ ‎l=N-‎2*(r-‎1)-1;‎/*边长*‎/b=‎(4*N-‎4)*(r‎-1)-4‎*(r-1‎)*(r-‎2)+1;‎/*本‎圈开始的数‎字*/‎p rint‎f("%4‎d",b+‎l*d+p‎l);/*‎打印数字*‎/} ‎prin‎t f("\‎n"); ‎}}‎‎第二种解法‎:这是用几‎何方法解的‎。

C#导出Excel的6种简单方法实现

C#导出Excel的6种简单方法实现

C#导出Excel的6种简单⽅法实现作者 | Johnson Manohar译者 | 谭开朗,责编 | 黄浩然出品 | CSDN(ID:CSDNnews)Syncfusion Excel (XlsIO) 库是⼀个 .Net Excel 库,它⽀持⽤户⽤ C# 和 以⼀个⾮常简易的⽅式,将各种数据源(如数据表,数组,对象集合,数据库,CSV / TSV,和微软⽹格控件等)数据导出到 Excel 。

将数据导出到 Excel 可以以更容易理解的⽅式可视化数据。

该特性有助于⽣成财务报告、银⾏报表和发票,同时还⽀持筛选⼤数据、验证数据、格式化数据等。

将数据导出到 Excel, Essential XlsIO 提供了以下⽅法:数据表导出到 Excel对象集合导出到 Excel数据库导出到 Excel微软⽹格控件导出到 Excel数组导出到 ExcelCSV 导出到 Excel在本⽂中,我们将研究这些⽅法以及如何执⾏它们。

数据表导出到 Excel 对象的数据(如 datatable 、datacolumn 和 dataview )可以导出到Excel ⼯作表。

通过识别列类型或单元格值类型、超链接和⼤型数据集,可以在⼏秒钟内将其导出并作为列标头。

将数据表导出到 Excel ⼯作表可以通过 ImportDataTable ⽅法实现。

下⾯的代码⽰例演⽰了如何将员⼯详细信息的数据表导出到Excel ⼯作表。

using (ExcelEngine excelEngine = new ExcelEngine()){IApplication application = excelEngine.Excel;application.DefaultVersion = ExcelVersion.Excel2016;//Create a new workbookIWorkbook workbook = application.Workbooks.Create(1);IWorksheet sheet = workbook.Worksheets[0];//Create a dataset from XML fileDataSet customersDataSet = new DataSet();customersDataSet.ReadXml(Path.GetFullPath(@"../../Data/Employees.xml"));//Create datatable from the datasetDataTable dataTable = new DataTable();dataTable = customersDataSet.Tables[0];//Import data from the data table with column header, at first row and first column,//and by its column type.sheet.ImportDataTable(dataTable, true, 1, 1, true);//Creating Excel table or list object and apply style to the tableIListObject table = sheet.ListObjects.Create("Employee_PersonalDetails", edRange);table.BuiltInTableStyle = TableBuiltInStyles.TableStyleMedium14;//Autofit the columnsedRange.AutofitColumns();//Save the file in the given pathStream excelStream = File.Create(Path.GetFullPath(@"Output.xlsx"));workbook.SaveAs(excelStream);excelStream.Dispose();}将数据表输出到Excel在将⼤数据导出到 Excel 时,如果不需要应⽤数字格式和样式,可以将其中importOnSave 参数的值设为 TRUE,使⽤ImportDataTable ⽅法重载。

C#中数据库数据如何导出至Excel表格

C#中数据库数据如何导出至Excel表格

C#中数据库数据如何导出至Excel表格有时候需要将数据库的数据导出至Excel表格表格,以便进行查看和分析,那么如何导出呢?下面用代码来实现。

首先,新建一个工程,需要添加引用Microsoft.Office.Interop.Excel.dll,以Oracle数据库为例(只要读出DataTable或DataSet就行了,哪种数据库没关系)。

1、创建一个表格,并插入如下数据。

[sql]view plaincopyprint?1.drop table TABLETESTEXCEL;2.create table TABLETESTEXCEL3.(4. col_id NUMBER not null,5. col_name VARCHAR2(32),6. col_age NUMBER,7. col_sex VARCHAR2(4),8. col_work VARCHAR2(32),9. col_mony FLOAT10.);数据:[sql]view plaincopyprint?1.insert into TABLETESTEXCEL (col_id, col_name, col_age, col_sex, col_work,col_mony)2.values (1, '吴一', 25, '男', '.NET', 5000);3.4.insert into TABLETESTEXCEL (col_id, col_name, col_age, col_sex, col_work,col_mony)5.values (2, '孙二', 24, '男', 'JAVA', 4999);6.7.insert into TABLETESTEXCEL (col_id, col_name, col_age, col_sex, col_work,col_mony)8.values (3, '张三', 25, '男', 'PHP', 5001);9.10.insert into TABLETESTEXCEL (col_id, col_name, col_age, col_sex, col_work,col_mony)11.values (4, '李四', 26, '男', 'DELPHI', 5002);12.13.insert into TABLETESTEXCEL (col_id, col_name, col_age, col_sex, col_work,col_mony)14.values (5, '王五', 27, '男', 'C++', 5003);15.16.insert into TABLETESTEXCEL (col_id, col_name, col_age, col_sex, col_work,col_mony)17.values (6, '赵六', 25, '男', 'C', 4008);18.19.insert into TABLETESTEXCEL (col_id, col_name, col_age, col_sex, col_work,col_mony)20.values (7, '燕七', 25, '男', '数据库', 4007);21.22.insert into TABLETESTEXCEL (col_id, col_name, col_age, col_sex, col_work,col_mony)23.values (8, '胡八', 25, '男', 'JSP', 5005);24.25.insert into TABLETESTEXCEL (col_id, col_name, col_age, col_sex, col_work,col_mony)26.values (9, '钱九', 25, '男', '', 4005);27.28.insert into TABLETESTEXCEL (col_id, col_name, col_age, col_sex, col_work,col_mony)29.values (10, '沈十', 25, '男', 'VB', 4000);mit;2、C#代码实现数据库操作的类:[csharp]view plaincopyprint?1.public class DataBaseHelper2. {3. public static DataTable ExecuterQuery(string connectionString, stringcommandSql)4. {5. DataTable dataTable = new DataTable();6.7. try8. {9. using (OracleConnection oracleConnection =10. new OracleConnection(connectionString))11. {12. oracleConnection.Open();13.14. using (OracleDataAdapter oracleDataAdapter =15. new OracleDataAdapter(commandSql,oracleConnection))16. {17. oracleDataAdapter.Fill(dataTable);18. }19.20. oracleConnection.Close();21. }22. }23. catch24. {25. return null;26. }27.28. return dataTable;29. }30. }[sql]view plaincopyprint?1.public class DataBaseDao2.{3. public static DataTable GetDataBaseTable()4. {5. string sql = " SELECT * FROM tableTestExcel";6.7. return DataBaseHelper.ExecuterQuery("User ID=downsoft;Password=sys;Data Source=orcl", sql);8. }9.}导出Excel的类:[csharp]view plaincopyprint?1.public class DataChangeExcel2.{3. /// <summary>4. /// 数据库转为excel表格5. /// </summary>6. /// <param name="dataTable">数据库数据</param>7. /// <param name="SaveFile">导出的excel文件</param>8. public static void DataSetToExcel(DataTable dataTable, string SaveFile)9. {10. Excel.Application excel;11.12. Excel._Workbook workBook;13.14. Excel._Worksheet workSheet;15.16. object misValue = System.Reflection.Missing.Value;17.18. excel = new Excel.ApplicationClass();19.20. workBook = excel.Workbooks.Add(misValue);21.22. workSheet = (Excel._Worksheet)workBook.ActiveSheet;23.24. int rowIndex = 1;25.26. int colIndex = 0;27.28. //取得标题29. foreach (DataColumn col in dataTable.Columns)30. {31. colIndex++;32.33. excel.Cells[1, colIndex] = col.ColumnName;34. }35.36. //取得表格中的数据37. foreach (DataRow row in dataTable.Rows)38. {39. rowIndex++;40.41. colIndex = 0;42.43. foreach (DataColumn col in dataTable.Columns)44. {45. colIndex++;46.47. excel.Cells[rowIndex, colIndex] =48.49. row[col.ColumnName].ToString().Trim();50.51. //设置表格内容居中对齐52. workSheet.get_Range(excel.Cells[rowIndex, colIndex],53.54. excel.Cells[rowIndex, colIndex]).HorizontalAlignment =55.56. Excel.XlVAlign.xlVAlignCenter;57. }58. }59.60. excel.Visible = false;61.62. workBook.SaveAs(SaveFile, Excel.XlFileFormat.xlWorkbookNormal, misValue,63.64. misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive,65.66. misValue, misValue, misValue, misValue, misValue);67.68. dataTable = null;69.70. workBook.Close(true, misValue, misValue);71.72. excel.Quit();73.74. PublicMethod.Kill(excel);//调用kill当前excel进程75.76. releaseObject(workSheet);77.78. releaseObject(workBook);79.80. releaseObject(excel);81.82. }83.84. private static void releaseObject(object obj)85. {86. try87. {88. System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);89. obj = null;90. }91. catch92. {93. obj = null;94. }95. finally96. {97. GC.Collect();98. }99. }100. }关闭进程的类:[csharp]view plaincopyprint?1.public class PublicMethod2.{3. [DllImport("User32.dll", CharSet = CharSet.Auto)]4.5. public static extern int GetWindowThreadProcessId(IntPtr hwnd, out intID);6.7. public static void Kill(Microsoft.Office.Interop.Excel.Application excel)8. {9. try10. {11. IntPtr t = new IntPtr(excel.Hwnd);12.13. int k = 0;14.15. GetWindowThreadProcessId(t, out k);16.17. System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(k);18.19. p.Kill();20. }21. catch22. { }23. }24.}写好了如上的类,那么开始调用吧,调用:[csharp]view plaincopyprint?1.DataChangeExcel.DataSetToExcel(DataBaseDao.GetDataBaseTable(),2.@"F:\outputFormDataBase.xls");这样成功将数据导出,如图。

C#输出Excel图表

C#输出Excel图表

Microsoft.Office.Interop.Excel.Range oResizeRange;Microsoft.Office.Interop.Excel.Series oSeries;//创建一个Excel对象(同时启动EXCEL.EXE进程)Microsoft.Office.Interop.Excel.Application m_Excel = newMicrosoft.Office.Interop.Excel.Application();m_Excel.Visible = true;m_Excel.SheetsInNewWorkbook = 1;//设置工作表的个数Microsoft.Office.Interop.Excel._Workbook m_Book =(Microsoft.Office.Interop.Excel._Workbook)(m_Excel.Workbooks.Add(System.Reflection.Missing.V alue));//添加新工作簿Microsoft.Office.Interop.Excel._Worksheet m_Sheet;m_Sheet = (Microsoft.Office.Interop.Excel._Worksheet)m_Excel.ActiveSheet;m_Book.Charts.Add(System.Reflection.Missing.Value, System.Reflection.Missing.Value, 1, System.Reflection.Missing.Value);m_Book.ActiveChart.ChartType =Microsoft.Office.Interop.Excel.XlChartType.xlColumnClustered;//设置图形xlColumnClusteredint num=2;m_Sheet.Cells[2, 1] = 100;m_Sheet.Cells[2, 2] = 200;m_Sheet.Cells[2, 3] = 180;//设置数据取值范围m_Book.ActiveChart.SetSourceData(m_Sheet.get_Range("A2", "C" + num.ToString()), Microsoft.Office.Interop.Excel.XlRowCol.xlColumns);//m_Book.ActiveChart.Location(Excel.XlChartLocation.xlLocationAutomatic, title);//以下是给图表放在指定位置m_Book.ActiveChart.Location(Microsoft.Office.Interop.Excel.XlChartLocation.xlLocationAsObjec t, m_);oResizeRange = (Microsoft.Office.Interop.Excel.Range)m_Sheet.Rows.get_Item(10,System.Reflection.Missing.Value);m_Sheet.Shapes.Item("Chart 1").Top = (float)(double)oResizeRange.Top; //调图表的位置上边距 oResizeRange = (Microsoft.Office.Interop.Excel.Range)m_Sheet.Columns.get_Item(6,System.Reflection.Missing.Value); //调图表的位置左边距// m_Sheet.Shapes.Item("Chart 1").Left = (float)(double)oResizeRange.Left;m_Sheet.Shapes.Item("Chart 1").Width = 400; //调图表的宽度m_Sheet.Shapes.Item("Chart 1").Height = 250; //调图表的高度m_Book.ActiveChart.PlotArea.Interior.ColorIndex = 19; //设置绘图区的背景色m_Book.ActiveChart.PlotArea.Border.LineStyle =Microsoft.Office.Interop.Excel.XlLineStyle.xlLineStyleNone;//设置绘图区边框线条m_Book.ActiveChart.PlotArea.Width = 400; //设置绘图区宽度//m_Book.ActiveChart.ChartArea.Interior.ColorIndex = 10; //设置整个图表的背影颜色//m_Book.ActiveChart.ChartArea.Border.ColorIndex = 8;// 设置整个图表的边框颜色m_Book.ActiveChart.ChartArea.Border.LineStyle =Microsoft.Office.Interop.Excel.XlLineStyle.xlLineStyleNone;//设置边框线条m_Book.ActiveChart.HasDataTable = false;//设置Legend图例的位置和格式m_Book.ActiveChart.Legend.Top = 20.00; //具体设置图例的上边距m_Book.ActiveChart.Legend.Left = 60.00;//具体设置图例的左边距m_Book.ActiveChart.Legend.Interior.ColorIndex =Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexNone;m_Book.ActiveChart.Legend.Width = 150;m_Book.ActiveChart.Legend.Font.Size = 9.5;//m_Book.ActiveChart.Legend.Font.Bold = true;m_ = "宋体";//m_Book.ActiveChart.Legend.Position = Excel.XlLegendPosition.xlLegendPositionTop;//设置图例的位置m_Book.ActiveChart.Legend.Border.LineStyle =Microsoft.Office.Interop.Excel.XlLineStyle.xlLineStyleNone;//设置图例边框线条//设置X轴的显示Microsoft.Office.Interop.Excel.Axis xAxis =(Microsoft.Office.Interop.Excel.Axis)m_Book.ActiveChart.Axes(Microsoft.Office.Interop.Excel. XlAxisType.xlValue, Microsoft.Office.Interop.Excel.XlAxisGroup.xlPrimary);xAxis.MajorGridlines.Border.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlDot; xAxis.MajorGridlines.Border.ColorIndex = 1;//gridLine横向线条的颜色xAxis.HasTitle = false;xAxis.MinimumScale = 1;xAxis.MaximumScale = 200; = "宋体";xAxis.TickLabels.Font.Size = 9;//设置Y轴的显示Microsoft.Office.Interop.Excel.Axis yAxis =(Microsoft.Office.Interop.Excel.Axis)m_Book.ActiveChart.Axes(Microsoft.Office.Interop.Excel. XlAxisType.xlCategory, Microsoft.Office.Interop.Excel.XlAxisGroup.xlPrimary);yAxis.TickLabelSpacing = 30;yAxis.TickLabels.NumberFormat = "M月D日";yAxis.TickLabels.Orientation =Microsoft.Office.Interop.Excel.XlTickLabelOrientation.xlTickLabelOrientationHorizontal;//Y轴显示的方向,是水平还是垂直等yAxis.TickLabels.Font.Size = 8; = "宋体";//设置标题和坐标轴m_Book.ActiveChart.HasTitle = true;m_Book.ActiveChart.ChartTitle.Text = "图表标题";m_Book.ActiveChart.Axes(Microsoft.Office.Interop.Excel.XlCategoryType xlCategory, Microsoft.Office.Interop.Excel.xlPrimary).HasTitle = true;//m_Book.ActiveChart.Axes(xlCategory, xlPrimary).AxisTitle.Characters.Text = "横坐标";//m_Book.ActiveChart.Axes(xlValue, xlPrimary).HasTitle = true;//m_Book.ActiveChart.Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = "纵坐标";/*//m_Book.ActiveChart.Floor.Interior.ColorIndex = 8;/***以下是设置标题*****m_Book.ActiveChart.HasTitle=true;m_Book.ActiveChart.ChartTitle.Text = "净值指数";m_Book.ActiveChart.ChartTitle.Shadow = true;m_Book.ActiveChart.ChartTitle.Border.LineStyle = Excel.XlLineStyle.xlContinuous;oSeries = (Microsoft.Office.Interop.Excel.Series)m_Book.ActiveChart.SeriesCollection(1);oSeries.Border.ColorIndex = 45;oSeries.Border.Weight = Microsoft.Office.Interop.Excel.XlBorderWeight.xlThick;oSeries = (Microsoft.Office.Interop.Excel.Series)m_Book.ActiveChart.SeriesCollection(2); oSeries.Border.ColorIndex = 9;oSeries.Border.Weight = Microsoft.Office.Interop.Excel.XlBorderWeight.xlThick;*/。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

// PivotalMatrix.cpp : Defines the entry point for the console application. //#include "stdafx.h"// Created by Yap Chun Wei// Version 1.0 (20 April 2006)// Version 1.1 (22 April 2006)// - Fixed bugs with compound files not being able to write files more than 65535 bytes.// - Fixed bugs with reading and writing to Excel files containing many strings.// Version 1.2 (30 April 2006)// - Added operator<< to pass BasicExcelCell to an output stream.// - Added Print() to BasicExcelWorksheet to print the worksheet to an output stream.// - Change BasicExcelCell Get functions to const functions.// - Rename BasicExcelWorksheet functions RenameWorkSheet() to Rename().// Version 1.3 (10 May 2006)// - Fixed bugs with reading from Excel files containing Asian characters. // Version 1.4 (13 May 2006)// - Fixed bugs with reading and writing to Excel files containing many strings.// Version 1.5 (15 May 2006)// - Remove code for ExtSST because it was causing problems with reading and writing to Excel files containing many strings.// Version 1.6 (16 May 2006)// - Optimized code for reading and writing.// Version 1.7 (22 May 2006)// - Fixed code to remove some warnings.// - Fixed bug with BasicExcelWorksheet::Cell.// - Fixed bug with BasicExcel::UpdateWorksheets().// Version 1.8 (23 May 2006)// - Fixed bug with reading Excel files containing many unicode strings.// - Fixed code to remove some warnings.// - Fixed variable code_ duplication in BoolErr.// - Minor changes to BasicExcelCell:Set functions.// Version 1.9 (24 May 2006)// - Changed name_ in Style from SmallString to LargeString.// - Fixed bug in BasicExcelCell::GetString andBasicExcelCell::GetWString.// - Minor changes to functions in BasicExcel and BasicExcelWorksheet which checks for unicode.// - Minor change to SmallString::Read.// Version 1.10 (30 May 2006)// - Fixed bug with reading Excel files containing many strings.// - Remove memory leaks.// Version 1.11 (2 June 2006)// - Fixed bug with reading and writing Excel files containing many unicode and ANSI strings.// Version 1.12 (6 June 2006)// - Fixed bug with reading and writing Excel files containing many unicode and ANSI strings.// Version 1.13 (1 August 2006)// - Changed BasicExcelCell::Get() so that it will get a stored double as an integer or vice versa if necessary.// - Changed BasicExcelCell::Get() so that it will not cause any errorsif a string is empty.// - Changed BasicExcelCell::SetString() andBasicExcelCell::SetWString() so that it will not save an empty string. // Version 1.14 (6 August 2006)// - Fixed bug with reading Excel files that contain a null string. #ifndef BASICEXCEL_HPP#define BASICEXCEL_HPP#pragma warning (disable : 4786)#pragma warning (disable : 4305)#pragma warning (disable : 4309)#pragma warning (disable : 4800)#pragma warning (disable : 4805)#include <algorithm>#include <cmath>#include <functional>#include <iostream>#include <iomanip>#include <fstream>#include <map>#include <vector>#include <string>#include <fstream>#include <windows.h>#include <string>#include <deque>#include <ctime>#include <sys/stat.h>#include <objbase.h>using namespace std;#define UTF16#ifdef UTF16#define SIZEOFWCHAR_T 2#else#define SIZEOFWCHAR_T sizeof(wchar_t)#endifnamespace YCompoundFiles{class Block// PURPOSE: In charge of handling blocks of data from a file{public:Block();// File handling functionsbool Create(const wchar_t* filename);bool Open(const wchar_t* filename, ios_base::openmodemode=ios_base::in | ios_base::out);bool Close();bool IsOpen();// Block handling functionsbool Read(size_t index, char* block);bool Write(size_t index, const char* block);bool Swap(size_t index1, size_t index2);bool Move(size_t from, size_t to);bool Insert(size_t index, const char* block);bool Erase(size_t index);bool Erase(vector<size_t>& indices);// Misc functionssize_t GetBlockSize() const {return blockSize_;}void SetBlockSize(size_t size){blockSize_ = size;indexEnd_ = fileSize_/blockSize_ + (fileSize_ % blockSize_ ? 1 : 0);}protected:vector<char> filename_;ios_base::openmode mode_;fstream file_;size_t blockSize_;size_t indexEnd_;size_t fileSize_;};struct LittleEndian{#define READWRITE(Type) \static void Read(const char* buffer, Type& retVal, int pos=0, int bytes=0)\{ \retVal = Type(0); \if (bytes == 0) bytes = sizeof(Type); \for (size_t i=0; i<bytes; ++i) \{ \retVal |= ((Type)((unsigned char)buffer[pos+i])) << 8*i;\} \} \static void ReadString(const char* buffer, Type* str, int pos=0, int bytes=0) \{ \for (size_t i=0; i<bytes; ++i) Read(buffer, str[i],pos+i*sizeof(Type)); \} \static void Write(char* buffer, Type val, int pos=0, int bytes=0)\{ \if (bytes == 0) bytes = sizeof(Type); \for (size_t i=0; i<bytes; ++i) \{ \buffer[pos+i] = (unsigned char)val; \val >>= 8; \} \} \static void WriteString(char* buffer, Type* str, int pos=0, int bytes=0)\{ \for (size_t i=0; i<bytes; ++i) Write(buffer, str[i],pos+i*sizeof(Type)); \} \static void Read(const vector<char>& buffer, Type& retVal, int pos=0, int bytes=0) \{ \retVal = Type(0); \if (bytes == 0) bytes = sizeof(Type); \for (size_t i=0; i<bytes; ++i) \{ \retVal |= ((Type)((unsigned char)buffer[pos+i])) << 8*i;\} \} \static void ReadString(const vector<char>& buffer, Type* str, int pos=0, int bytes=0) \{ \for (size_t i=0; i<bytes; ++i) Read(buffer, str[i],pos+i*sizeof(Type)); \} \static void Write(vector<char>& buffer, Type val, int pos=0, int bytes=0) \{ \if (bytes == 0) bytes = sizeof(Type); \for (size_t i=0; i<bytes; ++i) \{ \buffer[pos+i] = (unsigned char)val; \val >>= 8; \} \} \static void WriteString(vector<char>& buffer, Type* str, int pos=0, int bytes=0) \{ \for (size_t i=0; i<bytes; ++i) Write(buffer, str[i],pos+i*sizeof(Type)); \} \READWRITE(char)READWRITE(unsigned char)READWRITE(short)READWRITE(int)READWRITE(unsigned int)READWRITE(long)READWRITE(unsigned long)READWRITE(__int64)READWRITE(unsigned __int64)#undef READWRITEstatic void Read(const char* buffer, wchar_t& retVal, int pos=0, int bytes=0){retVal = wchar_t(0);if (bytes == 0) bytes = SIZEOFWCHAR_T;for (int i=0; i<bytes; ++i){retVal |= ((wchar_t)((unsigned char)buffer[pos+i])) << 8*i;}}static void ReadString(const char* buffer, wchar_t* str, int pos=0, int bytes=0){for (int i=0; i<bytes; ++i) Read(buffer, str[i],pos+i*SIZEOFWCHAR_T);}static void Write(char* buffer, wchar_t val, int pos=0, int bytes=0) {if (bytes == 0) bytes = SIZEOFWCHAR_T;for (int i=0; i<bytes; ++i){buffer[pos+i] = (unsigned char)val;val >>= 8;}}static void WriteString(char* buffer, wchar_t* str, int pos=0, int bytes=0){for (int i=0; i<bytes; ++i) Write(buffer, str[i],pos+i*SIZEOFWCHAR_T);}static void Read(const vector<char>& buffer, wchar_t& retVal, int pos=0, int bytes=0){retVal = wchar_t(0);if (bytes == 0) bytes = SIZEOFWCHAR_T;for (int i=0; i<bytes; ++i){retVal |= ((wchar_t)((unsigned char)buffer[pos+i])) << 8*i;}}static void ReadString(const vector<char>& buffer, wchar_t* str, int pos=0, int bytes=0){for (int i=0; i<bytes; ++i) Read(buffer, str[i],pos+i*SIZEOFWCHAR_T);}static void Write(vector<char>& buffer, wchar_t val, int pos=0, int bytes=0){if (bytes == 0) bytes = SIZEOFWCHAR_T;for (int i=0; i<bytes; ++i){buffer[pos+i] = (unsigned char)val;val >>= 8;}}static void WriteString(vector<char>& buffer, wchar_t* str, int pos=0, int bytes=0){for (int i=0; i<bytes; ++i) Write(buffer, str[i],pos+i*SIZEOFWCHAR_T);}};class CompoundFile{public:enum {DUPLICATE_PROPERTY=-6,NAME_TOO_LONG=-5, FILE_NOT_FOUND=-4,DIRECTORY_NOT_EMPTY=-3, DIRECTORY_NOT_FOUND=-2,INVALID_PATH=-1,SUCCESS=1};CompoundFile();~CompoundFile();// User accessible functionspublic:// Compound File functionsbool Create(const wchar_t* filename);bool Open(const wchar_t* filename, ios_base::openmodemode=ios_base::in | ios_base::out);bool Close();bool IsOpen();// Directory functionsint ChangeDirectory(const wchar_t* path);int MakeDirectory(const wchar_t* path);int PresentWorkingDirectory(wchar_t* path);int PresentWorkingDirectory(vector<wchar_t>& path);int RemoveDirectory(const wchar_t* path);int DelTree(const wchar_t* path);int DirectoryList(vector<vector<wchar_t> >& list, const wchar_t* path=0);// File functionsint MakeFile(const wchar_t* path);int RemoveFile(const wchar_t* path);int FileSize(const wchar_t* path, size_t& size);int ReadFile(const wchar_t* path, char* data);int ReadFile(const wchar_t* path, vector<char>&data);int WriteFile(const wchar_t* path, const char* data, size_t size);int WriteFile(const wchar_t* path, const vector<char>&data, size_t size);// ANSI char functionsbool Create(const char* filename);bool Open(const char* filename, ios_base::openmode mode=ios_base::in| ios_base::out);int ChangeDirectory(const char* path);int MakeDirectory(const char* path);int PresentWorkingDirectory(char* path);int PresentWorkingDirectory(vector<char>& path);int RemoveDirectory(const char* path);int DelTree(const char* path);int MakeFile(const char* path);int RemoveFile(const char* path);int FileSize(const char* path, size_t& size);int ReadFile(const char* path, char* data);int ReadFile(const char* path, vector<char>& data);int WriteFile(const char* path, char* data, size_t size);int WriteFile(const char* path, vector<char>& data, size_t size); // Protected functions and data membersprotected:// General functions and data membersvoid IncreaseLocationReferences(vector<size_t> indices);void DecreaseLocationReferences(vector<size_t> indices);void SplitPath(const wchar_t* path, wchar_t*& parentpath, wchar_t*& propertyname);vector<char> block_;Block file_;// Header related functions and data membersbool LoadHeader();void SaveHeader();class Header{public:Header();void Write(char* block);void Read(char* block);__int64 fileType_; // Magic number identifying this as a compound file system (0x0000)int uk1_; // Unknown constant(0x0008)int uk2_; // Unknown constant(0x000C)int uk3_; // Unknown constant(0x0010)int uk4_; // Unknown constant(0x0014)short uk5_; // Unknown constant (revision?) (0x0018)short uk6_; // Unknown constant (version?) (0x001A)short uk7_; // Unknown constant(0x001C)short log2BigBlockSize_; // Log, base 2, of the big block size (0x001E)int log2SmallBlockSize_; // Log, base 2, of the small block size (0x0020)int uk8_; // Unknown constant(0x0024)int uk9_; // Unknown constant(0x0028)int BATCount_; // Number of elements in the BAT array (0x002C)int propertiesStart_; // Block index of the first block of the property table (0x0030)int uk10_; // Unknown constant(0x0034)int uk11_; // Unknown constant(0x0038)int SBATStart_; // Block index of first big block containing the small block allocation table (SBAT) (0x003C)int SBATCount_; // Number of big blocks holding the SBAT (0x0040)int XBATStart_; // Block index of the first block in the Extended Block Allocation Table (XBAT) (0x0044)int XBATCount_; // Number of elements in the Extended Block Allocation Table (to be added to the BAT) (0x0048) int BATArray_[109]; // Array of block indices constituting the Block Allocation Table (BAT) (0x004C, 0x0050, 0x0054 ... 0x01FC)size_t bigBlockSize_;size_t smallBlockSize_;private:void Initialize();};Header header_;// BAT related functions and data membersvoid LoadBAT();void SaveBAT();size_t DataSize(size_t startIndex, bool isBig);size_t ReadData(size_t startIndex, char* data, bool isBig);size_t WriteData(const char* data, size_t size, int startIndex, bool isBig);void GetBlockIndices(size_t startIndex, vector<size_t>& indices, bool isBig);size_t GetFreeBlockIndex(bool isBig);void ExpandBATArray(bool isBig);void LinkBlocks(size_t from, size_t to, bool isBig);void FreeBlocks(vector<size_t>& indices, bool isBig);vector<int> blocksIndices_;vector<int> sblocksIndices_;// Properties related functions and data membersclass Property{public:Property();void Write(char* block);void Read(char* block);friend bool operator==(const Property& lhs, const Property& rhs){return (!wcscmp(_, _));}friend bool operator< (const Property& lhs, const Property& rhs){size_t maxLen1 = wcslen(_);size_t maxLen2 = wcslen(_);if (maxLen1 < maxLen2) return true;else if (maxLen1 > maxLen2) return false;else{int result = wcscmp(_, _);if (result <= 0) return true;else return false;}}friend bool operator!=(const Property& lhs, const Property& rhs) {return !(lhs == rhs);}friend bool operator> (const Property& lhs, const Property& rhs) {return (rhs < lhs);}friend bool operator<=(const Property& lhs, const Property& rhs) {return !(rhs < lhs);}friend bool operator>=(const Property& lhs, const Property& rhs) {return !(lhs < rhs);}wchar_t name_[32]; // A unicodenull-terminated uncompressed 16bit string (lblocke the high bytes) containing the name of the property. (0x00, 0x02, 0x04, ... 0x3E)short nameSize_; // Number of characters in the NAME field (0x40)unsigned char propertyType_; // Property type (directory, file, or root) Byte 1 (directory), 2 (file), or 5 (root entry) (0x42)unsigned char nodeColor_; // Node color (0x43)int previousProp_; // Previousproperty index (0x44)int nextProp_; // Next property index (0x48)int childProp_; // First child property index (0x4c)int uk1_;int uk2_;int uk3_;int uk4_;int uk5_;int seconds1_; // Seconds component of the created timestamp? (0x64)int days1_; // Days component of the created timestamp? (0x68)int seconds2_; // Seconds component of the modified timestamp? (0x6C)int days2_; // Days component of the modified timestamp? (0x70)int startBlock_; // Starting block of the file, used as the first block in the file and the pointer to the next block from the BAT (0x74)int size_; // Actual size of the file this property points to. (used to truncate the blocks to the real size). (0x78)};class PropertyTree{public:PropertyTree();~PropertyTree();PropertyTree* parent_;Property* self_;size_t index_;vector<PropertyTree*> children_;};void LoadProperties();void SaveProperties();int MakeProperty(const wchar_t* path, Property* property);PropertyTree* FindProperty(size_t index);PropertyTree* FindProperty(const wchar_t* path);PropertyTree* FindProperty(PropertyTree* parentTree, wchar_t* name);void InsertPropertyTree(PropertyTree* parentTree, Property* property, size_t index);void DeletePropertyTree(PropertyTree* tree);void UpdateChildrenIndices(PropertyTree* parentTree);void IncreasePropertyReferences(PropertyTree* parentTree, size_t index);void DecreasePropertyReferences(PropertyTree* parentTree, size_t index);PropertyTree* propertyTrees_;PropertyTree* currentDirectory_;vector<Property*> properties_;vector<PropertyTree*> previousDirectories_;};} // YCompoundFiles namespace endnamespace YExcel{using namespace YCompoundFiles;struct CODE{enum { FORMULA=0x0006, //Token array and the result of a formula cell.YEOF=0x000A, //End of a record block with leading BOF record.CALCCOUNT=0x000C, //Maximum number of times the forumlas should be iteratively calculatedCALCMODE=0x000D, //Calculate formulas manually, automatically, or automatically except for multiple table operationsPRECISION=0x000E, //Whether formulas use the real cell values for calculation or the values displayed on the screen.REFMODE=0x000F, //Method used to show cell addresses in formulas.DELTA=0x0010, //Maximum change of the result to exit an iteration.ITERATION=0x0011, //Whether iterations are allowed while calculating recursive formulas.PROTECT=0x0012, //Whether worksheet or a workbook is protected against modification.PASSWORD=0x0013, //16-bit hash value, calculated from the worksheet or workbook protection password.HEADER=0x0014, //Page header string for thecurrent worksheet.FOOTER=0x0015, //Page footer string for the current worksheet.EXTERNSHEET=0x0017, //List with indexes to SUPBOOK recordsNAME=0x0018, //Name and token array of an internal defined name.WINDOWPROTECT=0x0019, //Whether the window configuration of the document is protected.SELECTION=0x001D, //Addresses of all selected cell ranges and position of the active cell for a pane in the current sheet.DATEMODE=0x0022, //Base date for displaying date values.EXTERNNAME=0x0023, //Name of an external defined name, name of an add-in function, a DDE item or an OLE object storage identifier.LEFTMARGIN=0x0026, //Left page margin of the current worksheet.RIGHTMARGIN=0x0027, //Right page margin of the current worksheet.TOPMARGIN=0x0028, //Top page margin of the current worksheet.BOTTOMMARGIN=0x0029, //Bottom page margin of current worksheetPRINTHEADERS=0x002A, //Whether row and column headers (the areas with row numbers and column letters) will be printed.PRINTGRIDLINES=0x002B, //Whether sheet grid lines will be printed.FILEPASS=0x002F, //Information about the read/write password of the file.FONT=0x0031, //Information about a used font, including character formatting.TABLE=0x0036, //Information about a multiple operation table in the sheet.CONTINUE=0x003C, //Continue from previous recordWINDOW1=0x003D, //General settings for the workbook global settings.BACKUP=0x0040, //Make backup of file while saving?PANE=0x0041, //Position of window panes.CODEPAGE=0x0042, //Text encoding used to encode byte stringsDCONREF=0x0051,DEFCOLWIDTH=0x0055, //Default column width for columns that do not have a specific width setXCT=0x0059, //Number of immediately following CRN records.CRN=0x005A, //Contents of an external cell or cell range.FILESHARING=0x005B, //Information about write protection, for instance the write protection password.WRITEACCESS=0x005C, //Name of the user that has saved the file.UNCALCED=0x005E, //Formulas have not been recalculated before the document was saved.SAVERECALC=0x005F, //"Recalculate before save" optionOBJECTPROTECT=0x0063, //Whether objects of the current sheet are protected.COLINFO=0x007D, //Width for a given range of columnsGUTS=0x0080, //Layout of outline symbols.WSBOOL=0x0081, //16-bit value with boolean options for the current sheet.GRIDSET=0x0082, //Whether option to print sheet grid lines has ever been changed.HCENTER=0x0083, //Sheet is centred horizontally when printed.VCENTER=0x0084, //Whether sheet is centred vertically when printed.BOUNDSHEET=0x0085, //Sheet inside of the workbookWRITEPROT=0x0086, //Whether file is write protected.COUNTRY=0x008C, //User interface language of the Excel version that has saved the file, system regional settings at the time the file was saved.HIDEOBJ=0x008D, //Whether and how to show objects in the workbook.SORT=0x0090, //Last settings from the "Sort" dialogue for each sheet.PALETTE=0x0092, //Definition of all user-defined colours available for cell and object formatting.SETUP=0x00A1, //Page format settings of the current sheet.SHRFMLA=0x00BC, //Token array of a shared formula.MULRK=0x00BD, //Cell range containing RK value cells. All cells are located in the same row.MULBLANK=0x00BE, //Cell range of empty cells. All cells are located in the same row.DBCELL=0x00D7, //Relative offsets to calculate stream position of the first cell record for each row.BOOKBOOL=0x00DA, //Save values linked from external workbooks records and XCT records?SCENPROTECT=0x00DD, //Whether scenarios of the current sheet are protected.XF=0x00E0, //Formatting information for cells, rows, columns or styles.MERGEDCELLS=0x00E5, //All merged cell ranges of the current sheet.SST=0x00FC, //List of all strings used anywhere in the workbook.LABELSST=0x00FD, //Cell that contains a string.EXTSST=0x00FF, //Create a hash table with stream offsets to the SST record to optimise string search operations.LABELRANGES=0x015F, //Addresses of all row and column label ranges in the current sheet.USESELFS=0x0160, //Whether formulas in the workbook can use "natural language formulas".DSF=0x0161, //Whether file contains an addition BIFF5/BIFF7 workbook stream.SUPBOOK=0x01AE, //URL of an external document and a list of sheet names inside this document.CONDFMT=0x01B0, //List of cell range addresses for all cells with equal conditional formatting.CF=0x01B1, //Condition and the formatting attributes applied to the cells specified in the CONDFMT record, if the conditionis metDVAL=0x01B2, //List header of the data validity table in the current sheet.HLINK=0x01B8, //One cell address or a cell range where all cells contain the same hyperlink.DV=0x01BE, //Data validity settings and a list of cell ranges which contain these settings.DIMENSIONS=0x0200, //Range address of the used area in the current sheet.BLANK=0x0201, //Empty cell, contains cell address and formatting informationNUMBER=0x0203, //Cell that contains afloating-point value.BOOLERR=0x0205, //Error value cellSTRING=0x0207, //Result of a string formula.ROW=0x0208, //Properties of a single row in the sheet.INDEX=0x020B, //Range of used rows and stream positions of several records of the current sheet.ARRAY=0x0221, //Token array of an array formulaWINDOW2=0x023E, //Additional settings for the window of a specific worksheet.RK=0x027E, //Cell that contains an RK value (encoded integer or floating point value).STYLE=0x0293, //Name of a user-defined cell style or specific options for a built-in cell style.FORMAT=0x041E, //Number format.SHRFMLA1=0x04BC, //Token array of a shared formula (added).QUICKTIP=0x0800, //Cell range and text for a tool tip.BOF=0x0809, //Beginning of fileSHEETLAYOUT=0x0862, //Colour of the tab below the sheet containing the sheet name.SHEETPROTECTION=0x0867, //Additional options for sheet protection.RANGEPROTECTION=0x0868//Information about special protected ranges in a protected sheet.};};class Record{public:Record();virtual ~Record();virtual size_t Read(const char* data);virtual size_t Write(char* data);virtual size_t DataSize();virtual size_t RecordSize();short code_;vector<char> data_;size_t dataSize_;size_t recordSize_;vector<size_t> continueIndices_;};struct BOF : public RecordBOF();virtual size_t Read(const char* data);virtual size_t Write(char* data);short version_;short type_;short buildIdentifier_;short buildYear_;int fileHistoryFlags_;int lowestExcelVersion_;};struct YEOF : public Record{YEOF();};struct SmallString{SmallString();~SmallString();SmallString(const SmallString& s);SmallString& operator=(const SmallString& s);const SmallString& operator=(const char* str);const SmallString& operator=(const wchar_t* str);void Reset();size_t Read(const char* data);size_t Write(char* data);size_t DataSize();size_t RecordSize();size_t StringSize();wchar_t* wname_;char* name_;char unicode_;};struct LargeString{LargeString();~LargeString();LargeString(const LargeString& s);LargeString& operator=(const LargeString& s);const LargeString& operator=(const char* str);const LargeString& operator=(const wchar_t* str);void Reset();size_t Read(const char* data);size_t ContinueRead(const char* data, size_t size);size_t Write(char* data);size_t DataSize();size_t RecordSize();size_t StringSize();vector<wchar_t> wname_;vector<char> name_;char unicode_;short richtext_;int phonetic_;};class Workbook{public:Workbook();public:struct FileProtection;struct CodePage;struct DSF;struct TabID;struct FnGroupCount;struct WorkbookProtection;struct Window1 : public Record{Window1();virtual size_t Read(const char* data);virtual size_t Write(char* data);short horizontalPos_;short verticalPos_;short width_;short height_;short options_;short activeWorksheetIndex_;short firstVisibleTabIndex_;short selectedWorksheetNo_;short worksheetTabBarWidth_;};struct Backup;struct HideObj;struct DateMode;struct Precision;struct RefreshAll;struct BookBool;struct Font : public Record{Font();virtual size_t Read(const char* data);virtual size_t Write(char* data);virtual size_t DataSize();virtual size_t RecordSize();short height_;short options_;short colourIndex_;short weight_;short escapementType_;char underlineType_;char family_;char characterSet_;char unused_;SmallString name_;};struct Format;struct XF : public Record{XF();virtual size_t Read(const char* data);virtual size_t Write(char* data);short fontRecordIndex_;short formatRecordIndex_;short protectionType_;char alignment_;char rotation_;char textProperties_;char usedAttributes_;int borderLines_;int colour1_;short colour2_;};struct Style : public Record{Style();virtual size_t Read(const char* data);virtual size_t Write(char* data);virtual size_t DataSize();virtual size_t RecordSize();short XFRecordIndex_;char identifier_;char level_;LargeString name_;};struct Palette;struct UseSelfs;struct BoundSheet : public Record{BoundSheet();virtual size_t Read(const char* data);virtual size_t Write(char* data);virtual size_t DataSize();virtual size_t RecordSize();int BOFpos_;char visibility_;char type_;SmallString name_;};struct Country;struct LinkTable;struct SharedStringTable : public Record{SharedStringTable();virtual size_t Read(const char* data);virtual size_t Write(char* data);virtual size_t DataSize();virtual size_t RecordSize();int stringsTotal_;int uniqueStringsTotal_;vector<LargeString> strings_;};struct ExtSST : public Record{ExtSST();virtual size_t Read(const char* data);virtual size_t Write(char* data);virtual size_t DataSize();。

相关文档
最新文档