Browse Source

Merge pull request #272 from tokyis/master

Func. appending an existing sheet to a file
Geoffrey J. Teale 8 years ago
parent
commit
4da4be7c96
3 changed files with 40 additions and 4 deletions
  1. 4 4
      cell.go
  2. 13 0
      file.go
  3. 23 0
      file_test.go

+ 4 - 4
cell.go

@@ -114,21 +114,21 @@ func (c *Cell) SetFloatWithFormat(n float64, format string) {
 
 var timeLocationUTC, _ = time.LoadLocation("UTC")
 
-func timeToUTCTime(t time.Time) time.Time {
+func TimeToUTCTime(t time.Time) time.Time {
 	return time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), t.Nanosecond(), timeLocationUTC)
 }
 
-func timeToExcelTime(t time.Time) float64 {
+func TimeToExcelTime(t time.Time) float64 {
 	return float64(t.Unix())/86400.0 + 25569.0
 }
 
 // SetDate sets the value of a cell to a float.
 func (c *Cell) SetDate(t time.Time) {
-	c.SetDateTimeWithFormat(float64(int64(timeToExcelTime(timeToUTCTime(t)))), builtInNumFmt[14])
+	c.SetDateTimeWithFormat(float64(int64(TimeToExcelTime(TimeToUTCTime(t)))), builtInNumFmt[14])
 }
 
 func (c *Cell) SetDateTime(t time.Time) {
-	c.SetDateTimeWithFormat(timeToExcelTime(timeToUTCTime(t)), builtInNumFmt[22])
+	c.SetDateTimeWithFormat(TimeToExcelTime(TimeToUTCTime(t)), builtInNumFmt[22])
 }
 
 func (c *Cell) SetDateTimeWithFormat(n float64, format string) {

+ 13 - 0
file.go

@@ -133,6 +133,19 @@ func (f *File) AddSheet(sheetName string) (*Sheet, error) {
 	return sheet, nil
 }
 
+// Appends an existing Sheet, with the provided name, to a File
+func (f *File) AppendSheet(sheet Sheet, sheetName string) (*Sheet, error) {
+	if _, exists := f.Sheet[sheetName]; exists {
+		return nil, fmt.Errorf("duplicate sheet name '%s'.", sheetName)
+	}
+	sheet.Name = sheetName
+	sheet.File = f
+	sheet.Selected = len(f.Sheets) == 0
+	f.Sheet[sheetName] = &sheet
+	f.Sheets = append(f.Sheets, &sheet)
+	return &sheet, nil
+}
+
 func (f *File) makeWorkbook() xlsxWorkbook {
 	return xlsxWorkbook{
 		FileVersion: xlsxFileVersion{AppName: "Go XLSX"},

+ 23 - 0
file_test.go

@@ -252,6 +252,29 @@ func (l *FileSuite) TestAddSheetWithDuplicateName(c *C) {
 	c.Assert(err, ErrorMatches, "duplicate sheet name 'MySheet'.")
 }
 
+// Test that we can append a sheet to a File
+func (l *FileSuite) TestAppendSheet(c *C) {
+	var f *File
+
+	f = NewFile()
+	s := Sheet{}
+	sheet, err := f.AppendSheet(s, "MySheet")
+	c.Assert(err, IsNil)
+	c.Assert(sheet, NotNil)
+	c.Assert(len(f.Sheets), Equals, 1)
+	c.Assert(f.Sheet["MySheet"], Equals, sheet)
+}
+
+// Test that AppendSheet returns an error if you try to add two sheets with the same name
+func (l *FileSuite) TestAppendSheetWithDuplicateName(c *C) {
+	f := NewFile()
+	s := Sheet{}
+	_, err := f.AppendSheet(s, "MySheet")
+	c.Assert(err, IsNil)
+	_, err = f.AppendSheet(s, "MySheet")
+	c.Assert(err, ErrorMatches, "duplicate sheet name 'MySheet'.")
+}
+
 // Test that we can get the Nth sheet
 func (l *FileSuite) TestNthSheet(c *C) {
 	var f *File