當前位置: 首頁>>代碼示例>>C#>>正文


C# HSSFWorkbook.Write方法代碼示例

本文整理匯總了C#中NPOI.HSSF.UserModel.HSSFWorkbook.Write方法的典型用法代碼示例。如果您正苦於以下問題:C# HSSFWorkbook.Write方法的具體用法?C# HSSFWorkbook.Write怎麽用?C# HSSFWorkbook.Write使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在NPOI.HSSF.UserModel.HSSFWorkbook的用法示例。


在下文中一共展示了HSSFWorkbook.Write方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。

示例1: CreateExcel

        public ActionResult CreateExcel()
        {
            HSSFWorkbook wk = new HSSFWorkbook();
            ISheet tb = wk.CreateSheet("MyFirst");
            //創建一行,此行為第二行:創建行是從0開始
            IRow row = tb.CreateRow(1);
            ICell cell;
            for (int i = 0; i < 20; i++)
            {
                cell = row.CreateCell(i);  //在第二行中創建單元格
                cell.SetCellValue("This is a test");//循環往第二行的單元格中添加數據
            }
            //            ISheet tb = wk.CreateSheet("MyFirst");
            //            HSSFPatriarch patr = sheet.CreateDrawingPatriarch();
            //            HSSFComment comment1 = patr.CreateComment(new HSSFClientAnchor(0, 0, 0, 0, 1, 2, 4, 4));
            //            comment1.String = new HSSFRichTextString("Hello World");
            //            comment1.Author = "NPOI Team"
            //;
            //            cell.CellComment = comment1;

            FileStream fs = new FileStream(@"f:/test.xls", FileMode.Create);
            wk.Write(fs);
            fs.Close();
            return View();
        }
開發者ID:Golry,項目名稱:Bonsaii2,代碼行數:25,代碼來源:HomeController.cs

示例2: Generate

 /// <summary>
 ///     導出WOrd文件
 /// </summary>
 public void Generate()
 {
     //首先在內存中創建一個Excel文件
     var fileStream = new FileStream(outputPath, FileMode.OpenOrCreate);
     var workbook = new HSSFWorkbook();
     //創建一個表(sheet)--並獲取他
     var sheet = (HSSFSheet) workbook.CreateSheet("華中科技大學工程");
     //首先把需要多少個cell創建好----有多少個數據就有多少行--每行有3個數據
     for (var i = 0; i <= dataList.Count; i++)
     {
         sheet.CreateRow(i);
     }
     //創建表頭
     GenerateHeaderRow(workbook, sheet);
     //然後給每行---創建單元格---添加數據
     GenerateDataRow(workbook, sheet);
     try
     {
         //獲取目標文件流--寫入文件數據
         workbook.Write(fileStream);
         fileStream.Close();
     }
     catch (Exception e)
     {
         Console.Error.WriteLine(e.StackTrace);
         MessageBox.Show("文件導出失敗", "失敗");
         return;
     }
     finally
     {
         if (fileStream != null)
             fileStream.Close();
     }
     MessageBox.Show("Excel文件導出成功", "完成");
 }
開發者ID:ssthouse,項目名稱:NpoiTest,代碼行數:38,代碼來源:ExcelGenerator.cs

示例3: GenerateData

 MemoryStream GenerateData()
 {
     HSSFWorkbook hssfworkbook = new HSSFWorkbook();
     MemoryStream ms = new MemoryStream();
     var movies = (from m in db.Movies
                   select m).ToList();
     ISheet sheet1 = hssfworkbook.CreateSheet("Sheet1");
     IRow headerRow = sheet1.CreateRow(0);
     headerRow.CreateCell(0).SetCellValue("ID");
     headerRow.CreateCell(1).SetCellValue("電影名");
     headerRow.CreateCell(2).SetCellValue("發布日期");
     headerRow.CreateCell(3).SetCellValue("類型");
     headerRow.CreateCell(4).SetCellValue("價格");
     for (int i = 0; i < movies.Count; i++)
     {
         IRow Row = sheet1.CreateRow(i + 1);
         Row.CreateCell(0).SetCellValue(movies[i].ID);
         Row.CreateCell(1).SetCellValue(movies[i].Title);
         Row.CreateCell(2).SetCellValue(movies[i].ReleaseDate);
         Row.CreateCell(3).SetCellValue(movies[i].Genre);
         Row.CreateCell(4).SetCellValue(movies[i].Price.ToString());
     }
     hssfworkbook.Write(ms);
     return ms;
 }
開發者ID:txl1123,項目名稱:txl-solution,代碼行數:25,代碼來源:ExcelTestController.cs

示例4: ExportDataSetToExcel

        /// <summary>
        /// 由DataSet導出Excel
        /// </summary>
        /// <param name="sourceTable">要導出數據的DataTable</param>   
        /// <param name="sheetName">工作表名稱</param>
        /// <returns>Excel工作表</returns>   
        private static Stream ExportDataSetToExcel(DataSet sourceDs)
        {
            HSSFWorkbook workbook = new HSSFWorkbook();
            MemoryStream ms = new MemoryStream();

            for (int i = 0; i < sourceDs.Tables.Count; i++)
            {
                HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet(sourceDs.Tables[i].TableName);
                HSSFRow headerRow = (HSSFRow)sheet.CreateRow(0);
                // handling header.           
                foreach (DataColumn column in sourceDs.Tables[i].Columns)
                    headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
                // handling value.           
                int rowIndex = 1;
                foreach (DataRow row in sourceDs.Tables[i].Rows)
                {
                    HSSFRow dataRow = (HSSFRow)sheet.CreateRow(rowIndex);
                    foreach (DataColumn column in sourceDs.Tables[i].Columns)
                    {
                        dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());
                    }
                    rowIndex++;
                }
            }
            workbook.Write(ms);
            ms.Flush();
            ms.Position = 0;
            workbook = null;
            return ms;
        }
開發者ID:hanson-huang,項目名稱:cms,代碼行數:36,代碼來源:NPOIHelper.cs

示例5: Write

        public override void Write(Stream outStream)
        {
            Workbook workbook = new HSSFWorkbook();

            IEnumerable<User> users = User.SelectAll();
            foreach (User user in users)
            {
                IEnumerable<TimeBlock> timeBlocks = TimeBlock.SelectByUserAndDateRange(user.UserId, FromDate, ToDate);
                if (timeBlocks.Count() > 0)
                {
                    Sheet sheet = workbook.CreateSheet(user.Name);
                    Row header = sheet.CreateRow(0);
                    header.CreateCell(0).SetCellValue("Resource");
                    header.CreateCell(1).SetCellValue("Date");
                    header.CreateCell(2).SetCellValue("Client");
                    header.CreateCell(3).SetCellValue("Work Package");
                    header.CreateCell(4).SetCellValue("Hours");

                    int i = 1;
                    foreach (TimeBlock timeBlock in timeBlocks)
                    {
                        Row row = sheet.CreateRow(i ++);
                        row.CreateCell(0).SetCellValue(timeBlock.User.Name);
                        row.CreateCell(1).SetCellValue(timeBlock.Date.ToString("dd/MM/yy"));
                        row.CreateCell(2).SetCellValue(timeBlock.Job.Client.Name);
                        row.CreateCell(3).SetCellValue(timeBlock.JobId);
                        row.CreateCell(4).SetCellValue(Convert.ToDouble(timeBlock.Time));
                    }
                }
            }

            workbook.Write(outStream);
        }
開發者ID:colourblind,項目名稱:StopWastingMyTime,代碼行數:33,代碼來源:Report.cs

示例6: Main

        static void Main(string[] args)
        {
            //Excel worksheet combine example
            //You will be prompted to select two Excel files. test.xls will be created that combines the sheets
			//Note: This example does not check for duplicate sheet names. Your test files should have different sheet names.
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "Excel document (*.xls)|*.xls";
            ofd.Title = "Select first Excel document";
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                HSSFWorkbook book1 = new HSSFWorkbook(new FileStream(ofd.FileName, FileMode.Open));
                ofd.Title = "Select second Excel document";
                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    HSSFWorkbook book2 = new HSSFWorkbook(new FileStream(ofd.FileName, FileMode.Open));
                    HSSFWorkbook product = new HSSFWorkbook();

                    for (int i = 0; i < book1.NumberOfSheets; i++)
                    {
                        HSSFSheet sheet1 = book1.GetSheetAt(i) as HSSFSheet;
                        sheet1.CopyTo(product, sheet1.SheetName, true, true);
                    }
                    for (int j = 0; j < book2.NumberOfSheets; j++)
                    {
                        HSSFSheet sheet2 = book2.GetSheetAt(j) as HSSFSheet;
                        sheet2.CopyTo(product, sheet2.SheetName, true, true);
                    }
                    product.Write(new FileStream("test.xls", FileMode.Create, FileAccess.ReadWrite));
                }
                
            }
        }
開發者ID:89sos98,項目名稱:npoi,代碼行數:32,代碼來源:Program.cs

示例7: RenderDataSetToExcel

        private Stream RenderDataSetToExcel(DataSet ds) {
            MemoryStream ms = new MemoryStream();
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet;
            HSSFRow headerRow;

            //for (int k = ds.Tables.Count - 1, len = 0; len <= k; k--) {
            //    DataTable dt = ds.Tables[k];
            foreach(DataTable dt in ds.Tables) {
                sheet = (HSSFSheet)workbook.CreateSheet(dt.TableName);
                headerRow = (HSSFRow)sheet.CreateRow(0);

                foreach (DataColumn column in dt.Columns)
                    headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);

                int rowIndex = 1;
                foreach (DataRow row in dt.Rows) {
                    HSSFRow dataRow = (HSSFRow)sheet.CreateRow(rowIndex);

                    foreach (DataColumn column in dt.Columns) {
                        dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());
                    }

                    rowIndex++;
                }
            }
            workbook.Write(ms);
            ms.Flush();
            ms.Position = 0;

            sheet = null;
            headerRow = null;
            workbook = null;
            return ms;
        }
開發者ID:pczy,項目名稱:Pub.Class,代碼行數:35,代碼來源:ExcelWriter.cs

示例8: Main

        public static void Main(String[] args)
        {
            WriteJavaDoc();

            HSSFWorkbook wb = new HSSFWorkbook();
            SheetWriter sw = new SheetWriter(wb);

            NumberToTextConversionExamples.ExampleConversion[] exampleValues = NumberToTextConversionExamples.GetExampleConversions();
            for (int i = 0; i < exampleValues.Length; i++)
            {
                TestCases.SS.Util.NumberToTextConversionExamples.ExampleConversion example = exampleValues[i];
                sw.AddTestRow(example.RawDoubleBits, example.ExcelRendering);
            }

            MemoryStream baos = new MemoryStream();
            wb.Write(baos);
            byte[] fileContent = baos.ToArray();
            ReplaceNaNs(fileContent, sw.GetReplacementNaNs());

            FileInfo outputFile = new FileInfo("ExcelNumberRendering.xls");

            FileStream os = File.OpenWrite(outputFile.FullName);
            os.Write(fileContent, 0, fileContent.Length);
            os.Close();
            Console.WriteLine("Finished writing '" + outputFile.FullName + "'");
        }
開發者ID:hanwangkun,項目名稱:npoi,代碼行數:26,代碼來源:NumberRenderingSpreadsheetGenerator.cs

示例9: GetExcelBufferFromDataTable

        public byte[] GetExcelBufferFromDataTable(DataTable dt)
        {
            HSSFWorkbook hssfworkbook = new HSSFWorkbook();
            Sheet sheet = hssfworkbook.CreateSheet("Sheet1");

            sheet.CreateRow(0);
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                sheet.GetRow(0).CreateCell(i).SetCellValue(dt.Columns[i].ColumnName);
            }

            for (int i = 1; i <= dt.Rows.Count; i++)
            {
                sheet.CreateRow(i);
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    sheet.GetRow(i).CreateCell(j).SetCellValue(dt.Rows[i - 1][dt.Columns[j].ColumnName].ToString());
                }
            }

            MemoryStream memstream = new MemoryStream();
            try
            {
                hssfworkbook.Write(memstream);

                byte[] buffer = memstream.GetBuffer();

                return buffer;
            }
            finally
            {
                memstream.Close();
            }
        }
開發者ID:tagcosta,項目名稱:PerForms,代碼行數:34,代碼來源:Excel.cs

示例10: SaveFile

        public void SaveFile(string path, List<string> text)
        {
            var wb = new HSSFWorkbook();
            var sheet = wb.CreateSheet("Dictionary");

            int rowIndex = 0;
            var row = sheet.CreateRow(rowIndex);
            row.CreateCell(0).SetCellValue("Word");
            row.CreateCell(1).SetCellValue("Count");
            rowIndex++;

            foreach(var str in text)
            {
                var first = str.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries)[0];
                var second = str.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)[1];

                row = sheet.CreateRow(rowIndex);
                row.CreateCell(0).SetCellValue(first);
                row.CreateCell(1).SetCellValue(second);
                rowIndex++;
            }

            using(var fileStr = new FileStream(path, FileMode.Create))
            {
                wb.Write(fileStr);
            }
        }
開發者ID:aifabregaz,項目名稱:Reverse-Dictionary,代碼行數:27,代碼來源:XlsTextSaver.cs

示例11: Generate

 public FileResult Generate(SearchEntity searchEntity)
 {
     int num;
     var arrayData = this.GetArrayData(searchEntity, out num);
     var str = "根基對賬單";
     using (var stream = System.IO.File.OpenRead(base.Server.MapPath(string.Format("~/Excel/Market/{0}.xls", str))))
     {
         var xlBook = new HSSFWorkbook(stream);
         this.GenerateM1(arrayData, xlBook);
         this.GenerateM2(arrayData, xlBook);
         this.GenerateM3(arrayData, xlBook);
         if (xlBook.NumberOfSheets > 3)
         {
             xlBook.RemoveSheetAt(0);
             xlBook.RemoveSheetAt(0);
             xlBook.RemoveSheetAt(0);
             xlBook.FirstVisibleTab = 0;
         }
         var str3 = string.Format("{0}{1:yyMMddHHmmss}.xls", str, DateTime.Now);
         var path = string.Format(@"{0}Temp\{1}", AppDomain.CurrentDomain.BaseDirectory, str3);
         if (System.IO.File.Exists(path))
         {
             str3 = str3 + Guid.NewGuid().ToString() + ".xls";
             path = string.Format(@"{0}Temp\{1}", AppDomain.CurrentDomain.BaseDirectory, str3);
         }
         using (var stream2 = System.IO.File.OpenWrite(path))
         {
             xlBook.Write(stream2);
         }
         return this.File(path, "application/vnd.ms-excel", str3);
     }
 }
開發者ID:yangdan8,項目名稱:ydERPGJ,代碼行數:32,代碼來源:ReconciliationStatementController.cs

示例12: WriteToStream

 private static MemoryStream WriteToStream(HSSFWorkbook hssfworkbook)
 {
     //Write the stream data of workbook to the root directory
     MemoryStream file = new MemoryStream();
     hssfworkbook.Write(file);
     return file;
 }
開發者ID:Qlinzpc,項目名稱:Qizero4.5,代碼行數:7,代碼來源:ExcelHelper.cs

示例13: btnExport_Click

        //數據導出為Excel
        private void btnExport_Click(object sender, EventArgs e)
        {
            string sql = "select CC_AutoId,CC_CustomerName,CC_CellPhone,CC_Landline,CC_BuyDate,CC_CarNum,CC_BracketNum from T_Customers";
            using (SqlDataReader reader = SqlHelper.ExecuteReader(sql, CommandType.Text))
            {
                if (reader.HasRows)
                {

                    IWorkbook wb = new HSSFWorkbook();
                    ISheet sheet = wb.CreateSheet("customers");
                    int rowIndex = 0;//手動處理行索引
                    while (reader.Read())
                    {
                        int autoId = reader.GetInt32(0);
                        string name = reader.GetString(1);
                        string cellPhone = reader.GetString(2);
                        //數據為空,那麽就不能Get..,所以要在這裏判斷
                        string landLine = reader.IsDBNull(3) ? null : reader.GetString(3);//可為空

                        DateTime BuyDate = reader.GetDateTime(4);
                        string carNum = reader.GetString(5);
                        string bracketNum = reader.GetString(6);
                        IRow row = sheet.CreateRow(rowIndex);
                        rowIndex++;

                        row.CreateCell(0).SetCellValue(autoId);
                        row.CreateCell(1).SetCellValue(name);
                        row.CreateCell(2).SetCellValue(cellPhone);
                        //如果為空或Null,把Excel這個單元格設置為值為空
                        if (string.IsNullOrEmpty(landLine))
                        {
                            row.CreateCell(3).SetCellType(CellType.BLANK);
                        }
                        else
                        {
                            row.CreateCell(3).SetCellValue(landLine);
                        }

                        //============設置日期格式=======
                        //創建單元格樣式對象
                        ICellStyle cellStyle = wb.CreateCellStyle();
                        //設置單元格樣式對象屬性
                        cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("m/d/yy h:mm");
                        ICell BuyDateRow = row.CreateCell(4);
                        BuyDateRow.CellStyle = cellStyle;
                        BuyDateRow.SetCellValue(BuyDate);
                        //==============設置完成========

                        row.CreateCell(5).SetCellValue(carNum);
                        row.CreateCell(6).SetCellValue(bracketNum);

                    }
                    using (FileStream fs = File.OpenWrite("Customers.xls"))
                    {
                        wb.Write(fs);
                        MessageBox.Show("ok");
                    }
                }
            }
        }
開發者ID:RunningStudent,項目名稱:MyLearningCode_CSharp,代碼行數:61,代碼來源:Form1.cs

示例14: getExcel

        public static MemoryStream getExcel(DataTable dt, HttpContextBase content)
        {
            var book = new HSSFWorkbook();
            ISheet sheet = book.CreateSheet("Sheet1");
            IRow row = sheet.CreateRow(0);
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                row.CreateCell(i).SetCellValue(dt.Columns[i].ColumnName);
            }

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                IRow row2 = sheet.CreateRow(i + 1);
                for (int j = 0; j < dt.Columns.Count; j++)
                    row2.CreateCell(j).SetCellValue(dt.Rows[i][j].ToString());
            }


            //寫入到客戶端
            var ms = new MemoryStream();
            book.Write(ms);
            book = null;
            ms.Close();
            ms.Dispose();
            return ms;

        }
開發者ID:493409332,項目名稱:MT.Easyui,代碼行數:27,代碼來源:Excelcs.cs

示例15: Main

        static void Main(string[] args)
        {
            HSSFWorkbook hssfworkbook = new HSSFWorkbook();

            ////create a entry of DocumentSummaryInformation
            DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
            dsi.Company = "NPOI Team";
            hssfworkbook.DocumentSummaryInformation = dsi;

            ////create a entry of SummaryInformation
            SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
            si.Subject = "NPOI SDK Example";
            hssfworkbook.SummaryInformation = si;

            //here, we must insert at least one sheet to the workbook. otherwise, Excel will say 'data lost in file'
            //So we insert three sheet just like what Excel does
            hssfworkbook.CreateSheet("Sheet1");
            hssfworkbook.CreateSheet("Sheet2");
            hssfworkbook.CreateSheet("Sheet3");
            hssfworkbook.CreateSheet("Sheet4");

            ((HSSFSheet)hssfworkbook.GetSheetAt(0)).AlternativeFormula = false;
            ((HSSFSheet)hssfworkbook.GetSheetAt(0)).AlternativeExpression = false;

            //Write the stream data of workbook to the root directory
            FileStream file = new FileStream(@"test.xls", FileMode.Create);
            hssfworkbook.Write(file);
            file.Close();
        }
開發者ID:ctddjyds,項目名稱:npoi,代碼行數:29,代碼來源:Program.cs


注:本文中的NPOI.HSSF.UserModel.HSSFWorkbook.Write方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。